📎 Webclip
5 ways to center a div vertically and horizontally using CSS
The article gathers several CSS techniques for centering a div on a page. It frames the task as a common one and points to different layout tools that can place an element in the middle both horizontally and vertically.
Reading notes#
- Flex can center the child by setting the parent to
display: flexand usingjustify-content: centerwithalign-items: center, with fixed width and height on the parent. - Grid can center content with
display: gridandplace-items: centeron the parent. - Grid can also center through the child by setting
display: gridon the parent and usingalign-self: centerandjustify-self: centeron the child. - A positioning approach sets the child to
position: absoluteand moves it to 50% from the top and left of the parent. - A margin approach uses
margin: 0 autoon the child, though the author notes that this can be inconsistent and may need extra properties. - Another positioning method sets the child to
position: absolute, usestop,left,right, andbottomas0, and addsmargin: auto. - The note on
insetsays it is shorthand fortop,left,right, andbottom, and mentions Firefox support. - A bonus method uses CSS table layouts by setting
display: tableon a wrapper anddisplay: table-cellon the parent. - In the table approach, the child can be centered either with
marginor withdisplay: inline-block.
