I have seen that while developing websites, vertically centering a container (of fixed height) inside a container of random height always comes as a nightmare for the web developer (at least, me) while when it comes to horizontal centering a container (of fixed width) inside a container of random width, the margin:0px auto;
tends to serve an easy way out in the standard model.
When things can be as simple as that why doesn't CSS work out with the margin:auto 0px;
when it comes to centering a container of fixed height inside a container of random height? Is there any specific reason to do so?
The auto Value You can set the margin property to auto to horizontally center the element within its container. The element will then take up the specified width, and the remaining space will be split equally between the left and right margins.
The element must be block-level, e.g. display: block or display: table. The element must not float. The element must not have a fixed or absolute position.
It's really less of a nightmare than you think, just don't use margins. vertical-align
is really what you should rely on for fluid-height vertical centering. I threw together a quick demo to demonstrate my point:
* {
margin: 0;
padding: 0;
}
html,
body {
height: 100%;
text-align: center;
}
span {
height: 100%;
vertical-align: middle;
display: inline-block;
}
#any-height {
background: #000;
text-align: left;
width: 200px;
height: 200px;
vertical-align: middle;
display: inline-block;
}
<span></span>
<div id="any-height"></div>
See: http://jsfiddle.net/Wexcode/jLXMS/
The right answer for your question is that margin: auto 0
doesn't work the same way that margin: 0 auto
works because width: auto
doesn't work the same way height: auto
does.
Vertical auto margin works for absolutely positioned elements with a known height.
.parent {
position: relative;
}
.child {
position: absolute;
top: 0; right: 0; bottom: 0; left: 0;
width: 150px;
height: 150px;
margin: 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