使用margin:auto垂直对齐div [英] Using margin:auto to vertically-align a div

查看:175
本文介绍了使用margin:auto垂直对齐div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我知道如果我们使用 margin:0 auto; ,我们可以水平居中一个div。应该 margin:auto auto; 工作我怎么认为它应该工作?垂直居中?

So I know we can center a div horizontally if we use margin:0 auto;. Should margin:auto auto; work how I think it should work? Centering it vertically as well?

为什么 vertical-align:middle; 工作?

.black {
    position:absolute;
    top:0;
    bottom:0;
    left:0;
    right:0;
    background:rgba(0,0,0,.5);
}
.message {
    background:yellow;
    width:200px;
    margin:auto auto;
    padding:10px;
}

<div class="black">
    <div class="message">
        This is a popup message.
    </div>
</div>

JSFiddle

推荐答案

strong>您不能使用

You can't use:

vertical-align:middle http://www.w3.org/TR/CSS21/visudet.html#propdef-vertical-align =nofollow>是 不是 适用于封锁-level elements

vertical-align:middle because it's not applicable to block-level elements

margin-top:auto :auto ,因为其使用的值会计算为

margin-top:-50%因为基于百分比的利润率值是相对于 width 包含块

事实上,文档流的性质和元素高度计算算法无法使用边距将元素在其父元素内垂直居中。每当垂直边距的值改变时,它将触发父元素高度重新计算(回流),这将反过来触发原始元素的重新中心...使其成为无限循环。

In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.

您可以使用

这样的几个解决方法适用于你的场景;这三个元素必须像这样嵌套:

A few workarounds like this which work for your scenario; the three elements have to be nested like so:

.container {
    display: table;
    height: 100%;
    position: absolute;
    overflow: hidden;
    width: 100%;
}
.helper {
    #position: absolute;
    #top: 50%;
    display: table-cell;
    vertical-align: middle;
}
.content {
    #position: relative;
    #top: -50%;
    margin: 0 auto;
    width: 200px;
    border: 1px solid orange;
}

<div class="container">
    <div class="helper">
        <div class="content">
            <p>stuff</p>
        </div>
    </div>
</div

JSFiddle 根据Browsershot工作正常。

JSFiddle works fine according to Browsershot.

这篇关于使用margin:auto垂直对齐div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆