我正在尝试找到最有效的方法来将文本与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

其他回答

非常简单的解决方案,我在我的项目中多次使用它:

源代码

.welcome_box{
    height: 300px;
    display: flex;
    justify-content: center;
    align-content: center;
    flex-direction: column;
    border: solid 1px #dadada;
}

<div class="welcome_box">Hello Friends</div>

输出:

谢谢你提出这个问题。很高兴分享。

如果需要与min-height属性一起使用,则必须将此CSS添加到:

.outerContainer .innerContainer {
    height: 0;
    min-height: 100px;
}

在现代浏览器中,正确的方法是使用Flexbox。

有关详细信息,请参阅此答案。

请参阅下面的一些在旧浏览器中工作的旧方法。


CSS中的垂直居中http://www.jakpsatweb.cz/css/css-vertical-center-solution.html

文章摘要:

对于CSS2浏览器,可以使用display:table/display:table单元格来居中显示内容。

JSFiddle也提供了示例:

div{border:1px实心绿色;}<div style=“display:table;height:400px;溢出:隐藏;”><div style=“display:表格单元格;垂直对齐:中间;”><div>在现代IE8+和其他版本中,一切都是垂直居中的。</div></div></div>

可以使用#将旧浏览器(Internet Explorer 6/7)的黑客行为合并到样式中,以隐藏新浏览器的样式:

div{border:1px实心绿色;}<div style=“display:table;height:400px;#position:relative;overflow:hidden;”><div样式=“#位置:绝对;#顶部:50%;显示:表格单元格;垂直对齐:中间;”><div style=“#position:relative;#top:-50%”>一切都是垂直居中的</div></div></div>

使用CSS网格为我做到了:

.外部{背景色:灰色;宽度:10rem;高度:10rem;显示:栅格;对齐项目:中心;}.内部{背景色:#FF8585;对齐自身:中心;}<div class='outer'><div class='inner'>所容纳之物</div></div>

根据Adam Tomat的回答,我们准备了一个JSFiddle示例来对齐div中的文本:

<div class="cells-block">    
    text<br/>in the block   
</div>

通过在CSS中使用display:flex:

.cells-block {
    display: flex;
    flex-flow: column;
    align-items: center;       /* Vertically   */
    justify-content: flex-end; /* Horisontally */
    text-align: right;         /* Addition: for text's lines */
}

另一个例子和一篇博客文章中的一些解释。