【问题标题】:Vertical centering of an element with CSS (margin-top, top)使用 CSS 垂直居中元素(margin-top,top)
【发布时间】:2013-03-01 15:08:41
【问题描述】:

要将元素水平居中,将宽度设置为x,将左侧设置为50%,将margin-left 设置为-x/2。这与x = 50 % 完美配合(参见下面的示例)。为什么它不适用于垂直居中?下面的例子不起作用。

div.myDiv {
    width: 50%;
    height: 50%;
    left: 50%;
    top: 50%;
    margin-left: -25%;
    margin-top: -25%;
    position: absolute;
    border: 1px solid #555;
}
<div class="myDiv">I'm a div</div>

在 FF10 和 IE8 中使用 HTML 4.01 Transitional 进行测试,正文部分中只有一个 div-tag。

【问题讨论】:

标签: css


【解决方案1】:

您没有固定的宽度和高度(流体)。因此,您不能仅使用您在帖子中提到的 CSS 使 div 垂直居中。您需要使用 javascript 或 jQuery 来实现这一点。我以前做过这个,所以我只是在这里链接它。 https://stackoverflow.com/a/15293191/1577396


W3C 中所述,margin 属性包括margin-topmargin-bottom 指的是包含块的宽度(而不是高度),如果设置在percentages.

因此,您不能使用margin-topmargin-bottom 作为固定尺寸容器中的情况垂直对齐流体容器。

【讨论】:

  • 谢谢。我是这么想的,但为什么不可能呢?为什么IE和FF都支持水平居中而不支持垂直居中?
  • @user1904159 如果在percentages 中设置,边距值总是指包含块的宽度。因此,不可能进行垂直对齐,因为margin-topmargin-bottom 应该考虑height。检查此链接w3.org/TR/CSS2/box.html#margin-properties
  • 谢谢!非常有帮助。 :) 抱歉回复晚了。
【解决方案2】:

垂直居中可以在 css 中使用 display: table-cell 或摆弄 line-height 来完成 - 只是你玩的起点

【讨论】:

  • 除了&lt;div&gt;需要固定尺寸外,它也可以像OP一样完成
【解决方案3】:

试试这个:

div.myDiv {
margin: 0 auto;
}

auto will get you the horizontal centering you are looking for OR you can just set auto for the entire myDiv to get both vertical and horizontal centering.

div.myDiv {
margin:auto;
}

【讨论】:

    猜你喜欢
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-22
    • 1970-01-01
    • 2010-09-22
    • 2011-01-18
    相关资源
    最近更新 更多