我正在尝试找到最有效的方法来将文本与div对齐。我尝试了一些方法,但似乎没有一个有效。

.推荐文本{位置:绝对;左:15px;顶部:15px;宽度:150px;高度:309px;垂直对齐:中间;文本对齐:居中;字体系列:Georgia,“Times New Roman”,Times,serif;字体样式:斜体;填充:1em 0 1em 0;}<div class=“推荐文本”>Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididunt ut labore et dolore magna aliqua。在最低限度的威尼斯,quis nostrud exerciation ullamco labour nisi Ut aliquip ex a commo consequat。Duis aute irure多尔代表在voluptate velit esse cillum dolore eu fugiat nullapariator。除了你偶尔犯下的错误外,你还得承担责任,这是因为你在实验室里表现得很糟糕。</div>


当前回答

这是我找到的最干净的解决方案(InternetExplorer9+),并通过使用其他答案省略的转换样式,为“偏移0.5像素”问题添加了修复。

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

来源:垂直对齐任何东西,只需3行CSS

其他回答

这是在CSS中使用calc()的div模式中div的另一种变体。

<div style="height:300px; border:1px solid green;">
  Text in outer div.
  <div style="position:absolute; height:20px; top:calc(50% - 10px); border:1px solid red;)">
    Text in inner div.
  </div>
</div>

这是有效的,因为:

position:absolute用于在div中精确放置div我们知道内部div的高度,因为我们将其设置为20px。计算(50%-10px),用于对中内隔板高度的50%-一半

在网格项上自动边距。

与Flexbox类似,在网格项上应用自动边距会使其在两个轴上居中:

.container {
  display: grid;
}
.element {
  margin: auto;
}

使用显示器很容易:flex。使用以下方法,div中的文本将垂直居中:

第二部分{显示:-webkit flex;显示:柔性;对齐项目:居中;/*更多样式:*/高度:300px;背景色:#888;}<div>此处是您的文本。</div>

如果你愿意,水平:

第二部分{显示:-webkit flex;显示:柔性;对齐项目:居中;对齐内容:中心;/*更多样式:*/高度:300px;背景色:#888;}<div>此处是您的文本。</div>

您必须查看所需的浏览器版本;在旧版本中,代码不起作用。

尝试嵌入表元素。

<div><table style='width:200px;高度:100px;'><td style='vertical-align:middle;'>哥本哈根</td></table></div>

HTML格式:

<div class="col-md-2 ml-2 align-middle">
    <label for="option2" id="time-label">Time</label>
</div>

CSS:

.align-middle {
    margin-top: auto;
    margin-bottom: auto;
}