图片水平垂直居中、文字(多行文字)水平垂直居中,这是个老生常谈的问题,也经常有人提及这个问题,至此写个案例作为备忘。
主要用到的CSS属性就是display:table-cell[指定对象作为表格单元格。类同于html的td标签]。应用与已知外层容器宽高,但内部图片大小和文字数量未知的情况。
注:使用display:table-cell的时候,当前元素不支持margin和position属性,这个问题往往容易被人忽略。
CSS CODE:
body{ background:#202429; font-size:12px; line-height:18px;}
/* 公用容器 */
.box{
position:relative;
width:200px;
height:200px;
margin:40px auto 0 auto;
background:#282d33;
border:solid 1px #171717;
box-shadow:inset 0 0 1px rgba(255,255,255,0.4);
color:#bbb;
}
.box .tag{
position:absolute; top:-11px; left:70px;
width:60px; height:20px;
background:#1b1b1b;
border:solid 1px #171717;
text-align:center;
}
/* IE6+ 支持图片和多行文字水平垂直居中 */
.ie_imgText {
display:table;
width:200px;
height:200px;
text-align:center;
*position:relative;
}
.ie_imgText .cell {
vertical-align:middle;
display:table-cell;
*position:absolute;
*top:50%;
*left:50%;
}
.ie_imgText .content {
*position:relative;
*top:-50%;
*left:-50%;
}
/* IE6+ 图片水平垂直居中 */
.ie_img {
display:table-cell;
vertical-align:middle;
text-align:center;
width:200px;
height:200px;
*display:block;
*font-size:175px; /* 0.875 */
}
.ie_img img {
vertical-align:middle;
}
/* IE7+ */
.ie6_getOut {
width:200px;
height:200px;
display:table-cell;
text-align:center;
vertical-align:middle;
*line-height:200px; /* IE7 HACK */
}
HTML CODE:
<div class="box"> <div class="ie_imgText"> <div class="cell"> <div class="content"> <img src="2d.png" alt=""> <p>文字文字</p> <p>文字文字文字</p> </div> </div> </div> </div> <div class="box"> <div class="ie_img"> <img src="2d.png" alt=""> </div> </div> <div class="box"> <div class="ie6_getOut"> <img src="2d.png" alt=""> </div> </div>
Demo1 - 优点:兼容性和扩展性能得到较好的支持。缺点:层级过多。)
Demo2 - 优点:普普通通。缺点:需要计算font-size 会有略微误差。)
Demo3 - 优点:代码简洁实用。缺点:不支持IE6。)
这3个栗子大家可以根据自己的实际需求选择。
感谢您的阅读,本文由 蓝色梦想 版权所有。如若转载,请注明出处:蓝色梦想 - 图片、文字水平垂直居中(兼容各浏览器)