Why does auto attribute for margin not work vertically while it works horizontally?

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? Thanks for your insights in advance.


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:

HTML:

<span></span><div id="any-height"></div>

CSS:

* { 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; }

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;
}

css ----------------

.aligncenter{
      display: -webkit-box;
      display: -moz-box;
      display: box;
      -webkit-box-align: center;
      -moz-box-align: center;
      flex-align: center;
      -webkit-box-pack: center;
      -moz-box-pack: center;
      flex-pack: center;
}

html -------------------------

<div class="aligncenter">

---your content appear at the middle of the parent div----

</div>

note----------- this css class work with almost all browsers

链接地址: http://www.djcxy.com/p/41466.html

上一篇: CSS:将Div高度设置为100%

下一篇: 为什么边界的自动属性不能垂直工作,而是水平工作?