Best way to center a <div>
element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
Best way to center a <div>
element on a page both vertically and horizontally?
I know that margin-left: auto; margin-right: auto;
will center on the horizontal, but what is the best way to do it vertically, too?
There is actually a solution, using css3, which can vertically center a div of unknown height. The trick is to move the div down by 50%, then use
transformY
to get it back up to the middle. The only prerequisite is that the to-be-centered element has a parent. Example:Supported by all major browsers, and IE 9 and up (don't bother about IE 8, as it died together with win xp this autumn. Thank god.)
JS Fiddle Demo
Using Flex-box in my opinion:
You see there are only three CSS properties that you have to use to center the child element vertically and horizontally.
display: center;
Do the main part by just activating Flex-box display,justify-content: center;
center the child element vertically andalign-items: center;
center it horizontally. To see the best result I just add some extra styles :If you want to learn more about Flex-box you can visit W3Schools, MDN or CSS-Tricks for more information.
Using
display:grid
on parent and settingmargin:auto
to the centrerd elemnt will do the trick :See below snippet :
Solution
Using only two lines of CSS, utilizing the magical power of Flexbox
Explanation:
Give it an absolute positioning (the parent should have relative positioning). Then, the upper left corner is moved to the center. Because you don't know the width/height yet, you use css transform to translate the position relatively to the middle. translate(-50%, -50%) does reduce the x and y position of the upper left corner by 50% of width and height.
If you guys are using JQuery, you can do this by using
.position()
;CSS
Javascript (JQuery)
JSFiddle : http://jsfiddle.net/vx9gV/