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

后端 未结 3 897
鱼传尺愫
鱼传尺愫 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 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;
    }
    

提交回复
热议问题