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

后端 未结 3 895
鱼传尺愫
鱼传尺愫 2020-12-08 08:28

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 de

相关标签:
3条回答
  • 2020-12-08 08:38

    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/

    0 讨论(0)
  • 2020-12-08 08:53

    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

    0 讨论(0)
  • 2020-12-08 09:03

    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;
    }
    
    0 讨论(0)
提交回复
热议问题