【问题标题】:Vertically and horizontally centering text within a div在 div 中垂直和水平居中文本
【发布时间】:2012-03-14 21:47:26
【问题描述】:

我有一个 div,其中包含一个覆盖有文本的图形背景。我想水平和垂直居中这个元素。但我无法让文本垂直居中。到目前为止,我有以下代码:

<div id="step">
    <div id="background">
        <img src="buttonbackground.png" class="stretch" alt="" />
    </div>
    <div>
       <h3>some text</h3>
    </div>
</div>

在 CSS 中:

#background {
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px;
    z-index: -1;
}

#step {
    text-align:center;
    color:white;
}

.stretch {
    width:200px;
    height:40px;
}

使用我在其他地方经常引用的表格单元格/垂直对齐技术不太奏效。

【问题讨论】:

    标签: css


    【解决方案1】:

    鉴于它是H3,我假设它是一个标题,所以它可能是一行文本。如果是这种情况,只需将h3line-height设置为容器的高度。

    如果它是一个段落,你可以这样做:

    #centeredDiv {
      position:absolute;
      top: 50%;
      left: 50%
      margin-top:-20px ;(half the height of the container)
      margin-left: -100px; (half the width of the container)
    

    }

    不要将像素与百分比混合。

    【讨论】:

      【解决方案2】:

      试试:

      #step {
          text-align: center;
          vertical-align: center;
          color: white;
          height: 40px;
      }
      

      编辑:

      或者,您可以尝试将#background 的高度显式设置为 40 像素而不是 100%。应该可以达到同样的效果。

      【讨论】: