居中方案列举
以下是工作中对居中的一些总结列表,虽然点不大,但是还是可以发散一下思维角度。如果有更好的方案,也可以贴出来大家讨论一下。
单行文本居中的方案line-height
<div style="height:100px;line-height:100px;text-align: center;width:200px;border:1px solid #39f;">
单行居中
</div>
多行居中的方案,table方案单元格默认vertical-align:middle
<table style="border: 1px solid #39f;height:100px;width:200px;">
<tr>
<td>多行居中的多行居中的</td>
<td>行居中的多行居中的行居中的多行居中的行居中的多行居中的行居中的多行居中的</td>
</tr>
</table>
多行垂直居中的方案,采用display:table(ie8>=),chrome ff可行
<style>
#J_p3{
width:200px;
height: 100px;
display:table;
border:1px solid #39f;
}
#J_p3 p{
display:table-cell;
height:100px;
vertical-align:middle;
}
</style>
<div id="J_p3">
<p>
多行居中的多行居中的
</p>
</div>
多行垂直居中的方案,采用after伪类(ie8>=),chrome ff可行
<style>
#J_p4{
width:200px;
height: 100px;
border:1px solid #39f;
}
#J_p4:after{
display:inline-block;
width:0;
height:100%;
vertical-align:middle;
content:'';
}
#J_p4 p{
display:inline-block;
vertical-align:middle;
}
</style>
<div id="J_p4">
<p>
多行居中的多行居中的
</p>
</div>
多行垂直居中的方案,占位标签(<font color="red">全浏览器推荐方案</font>,所有浏览器都可行)
<style>
#J_p5{
width:200px;
height: 100px;
border:1px solid #39f;
}
#J_p5 p{
display:inline-block;
vertical-align:middle;
}
#J_p5 .after{
display:inline-block;
*display: inline;
*zoom:1;
vertical-align:middle;
width:0;
height:100%;
}
</style>
<div id="J_p5">
<p>
多行居中的多行居中的
</p>
<div class="after"></div>
</div>
多行垂直居中的方案,flex布局 (需要浏览器支持css3才可行,h5居多)
<style>
#J_p6 {
width:200px;
height: 100px;
border:1px solid #39f;
display: flex;
justify-content:center;
align-items: center;
}
#J_p6 p {
border:1px solid red;
width:100px;
word-wrap: break-word;
}
</style>
<div id="J_p6">
<p>
多行居中的多行居中的
</p>
</div>
多行垂直的方案,transform的方案(ie8+需要浏览器支持css3才可行,h5居多)
<style>
#J_p7{
position: relative;
width:200px;
height: 100px;
border:1px solid #39f;
}
#J_p7 .f1{
position: absolute;
top:50%;
left:50%;
background: red;
/*width: 160px;*/
/*height: 80px;*/
transform: translateX(-50%) translateY(-50%);
}
</style>
<div id="J_p7">
<div class="f1">多行居中的多行居中的</div>
</div>
容器垂直的方案,margin:auto方案,必须声明容器的内容体宽高(不推荐),(ie8>=),chrome ff可行。
<style>
#J_p8{
position: relative;
width:200px;
height: 100px;
border:1px solid #39f;
}
#J_p8 .f1{
position: absolute;
display: inline-block;
top:0;left:0;bottom:0;right:0;margin:auto;
background: red;
}
</style>
<div id="J_p8">
<div class="f1">xxxxx</div>
</div>
网友评论