我正在尝试找到最有效的方法来将文本与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>
这些天(我们不再需要InternetExplorer6-8),我只会使用CSS display:table(或display:flex)来解决这个问题。
表:.vcenter(.v中心){显示:表格;背景:#eee;/*可选的*/宽度:150px;高度:150px;文本对齐:居中;/*可选的*/}.vcenter>:第一个子级{显示:表格单元格;垂直对齐:中间;}<div class=“vcenter”><p>这是我的文本</p></div>
弯曲:.vcenter(.v中心){显示:柔性;对齐项目:居中;高度:150px;对齐内容:中心;/*可选的*/背景:#eee;/*可选的*/宽度:150px;}<div class=“vcenter”><p>这是我的文字</p></div>
对于较旧的浏览器:
这是(实际上是)我最喜欢的解决方案(简单且非常受浏览器支持):
第二部分{边距:5px;文本对齐:居中;显示:内联块;}.vcenter(.v中心){背景:#eee;/*可选的*/宽度:150px;高度:150px;}.vcenter:之前{内容:“”;显示:内联块;高度:100%;垂直对齐:中间;最大宽度:0.001%;/*为了防止文本换行,你不应该注意到它*/}.vcenter>:第一个子级{显示:内联块;垂直对齐:中间;最大宽度:99.999%;}<div class=“vcenter”><p>这是我的文字</p></div><div class=“vcenter”><h4>这是我的文本<br/>文本</br/>文本</h4></div><div class=“vcenter”><div><p>这是我的</p><p>文本</p></div></div>
在现代浏览器中,正确的方法是使用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>
有一种更简单的方法可以垂直对齐内容,而无需诉诸表格/表格单元格:
http://jsfiddle.net/bBW5w/1/
在其中,我添加了一个不可见的(width=0)div,它假设容器的整个高度。
它似乎可以在Internet Explorer和Firefox(最新版本)中使用。我没有检查其他浏览器
<div class="t">
<div>
everything is vertically centered in modern IE8+ and others.
</div>
<div></div>
</div>
当然,CSS:
.t, .t > div:first-child
{
border: 1px solid green;
}
.t
{
height: 400px;
}
.t > div
{
display: inline-block;
vertical-align: middle
}
.t > div:last-child
{
height: 100%;
}
HTML
<div class="relative"><!--used as a container-->
<!-- add content here to to make some height and width
example:<img src="" alt=""> -->
<div class="absolute">
<div class="table">
<div class="table-cell">
Vertical contents goes here
</div>
</div>
</div>
</div>
CSS
.relative {
position: relative;
}
.absolute {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
background: rgba(0, 0, 0, 0.5);
}
.table {
display: table;
height: 100%;
width: 100%;
text-align: center;
color: #fff;
}
.table-cell {
display: table-cell;
vertical-align: middle;
}