步骤 2 : 内边距方式 步骤 3 : table方式 <style>
#d {
line-height: 100px;
}
div{
border:solid 1px lightskyblue;
}
</style>
<div id="d">line-height 适合单独一行垂直居中</div>
<style> #d { line-height: 100px; } div{ border:solid 1px lightskyblue; } </style> <div id="d">line-height 适合单独一行垂直居中</div>
借助设置相同的上下内边距,实现垂直居中效果,可以用在多行文本上
<style>
#d {
padding: 30 0;
}
div{
border:solid 1px lightskyblue;
}
</style>
<div id="d">多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 </div>
<style> #d { padding: 30 0; } div{ border:solid 1px lightskyblue; } </style> <div id="d">多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 多行内容 </div>
首先通过display: table-cell;把div用单元格的形式显示,然后借用单元格的垂直居中vertical-align: middle; 来达到效果。
这样对图片也可以居中,上一步 line-height就不能对图片居中。 <style>
#d {
display: table-cell;
vertical-align: middle;
height:200px;
}
div{
border:solid 1px lightskyblue;
}
</style>
<div id="d">
<img src="https://how2j.cn/example.gif">
</div>
<style> #d { display: table-cell; vertical-align: middle; height:200px; } div{ border:solid 1px lightskyblue; } </style> <div id="d"> <img src="https://how2j.cn/example.gif"> </div>
HOW2J公众号,关注后实时获知最新的教程和优惠活动,谢谢。
提问已经提交成功,正在审核。 请于 我的提问 处查看提问记录,谢谢
|