水平居中和垂直居中已经单独介绍过,本文将介绍水平垂直同时居中的5种思路
思路一: text-align + line-height实现单行文本水平垂直居中
CSS Code复制内容到剪贴板
<style>
.test{
text-align: center;
line-height: 100px;
}
</style>
XML/HTML Code复制内容到剪贴板
<div class="test" style="background-color: lightblue;width: 200px;">测试文字</div>
思路二: text-align + vertical-align
【1】在父元素设置text-align和vertical-align,并将父元素设置为table-cell元素,子元素设置为inline-block元素
[注意]若兼容IE7-浏览器,将结构改为<table>结构来实现table-cell的效果;用display:inline;zoom:1;来实现inline-block的效果CSS Code复制内容到剪贴板
<style>
.parent{
display: table-cell;
text-align: center;
vertical-align: middle;
}
.child{
display: inline-block;
}
</style>
XML/HTML Code复制内容到剪贴板
<div class="parent" style="background-color: gray; width:200px; height:100px;">
<div class="child" style="background-color: lightblue;">测试文字</div>
</div>
【2】若子元素是图像,可不使用table-cell,而是其父元素用行高替代高度,且字体大小设为0。子元素本身设置vertical-align:middle
CSS Code复制内容到剪贴板
<style>
.parent{
text-align: center;
line-height: 100px;
font-size: 0;
}
.child{
vertical-align: middle;
}
</style>
XML/HTML Code复制内容到剪贴板
<div class="parent" style="background-color: gray; width:200px; ">
<img class="child" src="http://huoche.7234.cn/images/jb51/xpn0y02dhpx.gif" width="50%" alt="test">
</div>
思路三: margin + vertical-align
要想在父元素中设置vertical-align,须设置为table-cell元素;要想让margin:0 auto实现水平居中的块元素内容撑开宽度,须设置为table元素。而table元素是可以嵌套在tabel-cell元素里面的,就像一个单元格里可以嵌套一个表格
新闻热点
疑难解答