【问题标题】:How do I center the div vertically? [duplicate]如何使 div 垂直居中? [复制]
【发布时间】:2011-05-25 00:41:31
【问题描述】:

可能重复:
What's The Best Way of Centering a Div Vertically with CSS

.title_text_only{
position:absolute;
width:100%;
display:none;
z-index:9;
top:50%;
bottom:50%;
text-align:center;
color:#fff;
font-size:18px;
text-shadow: 1px 1px 1px #666;
}

现在,它似乎不起作用。前 50% 不垂直居中。这有点落伍了。好像上边框是 50%。

【问题讨论】:

  • 先尝试添加任意高度

标签: javascript jquery html css vertical-alignment


【解决方案1】:

如果可以指定框的高度,可以使用margin-top: -[height / 2]px(填写[height / 2],注意大多数浏览器会在100%缩放时将小数像素向上取整)。

如果你可以指定其父级的高度,你可以这样做:

parent {
    height: [height]px;
}
child {
    /* Make the element part of the inline flow, as vertical-align isn't supported on block elements */
    display: -moz-inline-box; /* Old Firefox doesn't support inline-block */
    display: inline-block;
    /* IE < 8 doesn't support inline-block on native block-level elements */
    *display: inline;
    *zoom: 1;

    /* The interesting bit */
    line-height: [height]px;
    vertical-align: middle;
}

如果子项的内容预计会换行成多行,您可以将其换行在重置line-height 的子子项中。

【讨论】:

    【解决方案2】:
    【解决方案3】:

    top: 50%; 完全符合您的怀疑:它将顶部 edge 放置在 50% 的高度。您还可以通过应用等于元素高度一半的负垂直边距来抵消这种影响。例如,如果元素是 100px 高,你可以添加这个属性:

    margin-top: -50px;
    

    【讨论】:

      【解决方案4】:

      如果元素的高度是固定的,则执行以下操作

      CSS:

      .title_text_only{
      position:absolute;
      width:100%;
      display:none;
      z-index:9;
      **top:50%;**
      bottom:50%;
      text-align:center;
      color:#fff;
      font-size:18px;
      text-shadow: 1px 1px 1px #666;
      **margin-top: -(half the height)**
      }
      

      如果要垂直居中动态高度的 div,则需要 javascript..

      document.getElementById('myElement').style.marginTop = (-1) * document.getElementById('myElement').offsetHeight / 2
      

      【讨论】:

        猜你喜欢
        • 2011-05-20
        • 2011-05-23
        • 2014-02-15
        • 2014-07-15
        • 2018-06-21
        • 2013-02-15
        • 2017-06-30
        • 1970-01-01
        相关资源
        最近更新 更多