I know that margin-top in percentages are relative to the width... That's why, I can't always vertically and horizontally center a div that is 50% height, and 50% width of the full screen.
http://jsfiddle.net/8BJ94/
When you resize, the margin-top is relative to the width
CSS
#mini {
height : 50%;
width : 50%;
background-color : #FFFFFF;
margin-top : 25%;
margin-left : 25%;
}
http://jsfiddle.net/8BJ94/1/
#hello {
position : absolute;
width : 100%;
height : 100%;
background-color : #123456;
text-align: center;
}
#hello:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
#mini {
height : 50%;
width : 50%;
background-color : #FFFFFF;
display: inline-block;
vertical-align: middle;
}
Based on http://css-tricks.com/centering-in-the-unknown/
Horizontal centering (easy):
#hello {
text-align: center;
}
#mini {
display: inline-block;
}
Vertical centering:
Make line's height to be 100% height with a ghost element:
#hello:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
}
Center #mini
vertically (relatively to that line) with vertical-align
:
#mini {
display: inline-block;
vertical-align: middle;
}
Essentially everything and IE 8+.
You can support IE7 too if you use a real element as a ghost, instead of a :before
pseudo element. But it isn't semantically correct.
Here is the best approach: (live example). It is supported in all modern browsers. Reference.
Set the html
/body
elements to height:100%
and width:100%
.
Then set the display of the body, or the parent element to table
.
Finally, use display:table-cell
, and vertical-align:middle
on the child element.
That will take care of the vertical alignment.
In order to center horizontally, set margin:0px auto
on the child element.
In certain cases where the width of the child isn't defined or is dynamically generated, you can also use text-align:center
assuming it is an inline
element.
HTML
<div id="parent">
<div id="child"></div>
</div>
CSS
html, body {
height:100%;
width:100%;
margin:0px;
}
body {
display:table;
}
#parent {
display:table-cell;
vertical-align:middle;
background:#123456;
}
#child {
height:50%;
width:50%;
background:white;
margin:0px auto;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With