我有一个包含文本的<div>元素,我想将这个<div>的内容垂直居中对齐。

这是我的<div>风格:

#盒子{高度:170px;宽度:270px;背景:#000;字体大小:48px;颜色:#FFF;文本对齐:居中;}<div id=“box”>Lorem ipsum悲哀坐</div>

实现这一目标的最佳方式是什么?


当前回答

<!DOCTYPE html>
<html>
  <head>
    <style>
      .main{
        height:450px;
        background:#f8f8f8;
        display: -ms-flexbox;
        display: -webkit-flex;
        display: flex;
        -ms-flex-align: center;
        -webkit-box-align: center;
        align-items: center;
        justify-content: center;
        width: 100%;
      }
    </style>
  </head>
  <body>
    <div class="main">
      <h1>Hello</h1>
    </div>
  </body>
</html>

其他回答

如果你不在乎它的视觉3D效果,就在button而不是div中设置它。

#盒子{高度:120px;宽度:300px;背景:#000;字体大小:48px;字体样式:倾斜;颜色:#FFF;}<button Id=“box”禁用>Lorem ipsum dolor坐amet,consectetur adipiscing elit。</按钮>

一种更好、更简单、更快速的方法是将CSS中的页边空白设置为45%左右:

margin-top: 45%;

你可能需要玩这个数字,但它将位于周围分区的中心。

这非常有效。

您必须为div使用表样式,为内容使用居中对齐。

.text{
   background: #ccc;
   position: relative;
   float: left;
   text-align: center;
   width: 400px;
   line-height: 80px;
   font-size: 24px;
   color: #000;
   float: left;
 }

简单而通用的方法是表格方法):

[ctrv]{
    display: table !important;
}

[ctrv] > *{ /* Addressing direct descendants */
      display: table-cell;
      vertical-align: middle;
      // text-align: center; /* Optional */
}

在父标记上使用此属性(或等效的类)甚至可以使许多子标记对齐:

<parent ctrv>  <ch1/>  <ch2/>   </parent>