在网页中我们多使用css+div进行布局,我们通常会将图片放在div中,那么该如何让图片在DIV盒子里水平居中。下面我们来看一下css设置图片在div中居中的方法。
css3使div图片居中的方法:
1、利用display:table-cell,具体代码如下
html代码
css代码.img_wrap{
width: 400px;
height: 300px;
border: 1px dashed #ccc;
display: table-cell; //主要是这个属性
vertical-align: middle;
text-align: center;
}
效果如下:
2、采用背景法:
html代码
css代码.img_wrap{
width: 400px;
height: 300px;
border: 1px dashed #ccc;
background: url(wgs.jpg) no-repeat center center;
}
效果如下
3、图片外面用个p标签,通过设置line-height使图片垂直居中:
html代码
css代码*{margin: 0px;padding: 0px}
.img_wrap{
width: 400px;
height: 300px;
border: 1px dashed #ccc;
text-align: center;}
.img_wrap p{
width:400px;
height:300px;
line-height:300px; /* 行高等于高度 */
}
.img_wrap p img{
*margin-top:expression((400 - this.height )/2); /* CSS表达式用来兼容IE6/IE7 */
vertical-align:middle;
border:1px solid #ccc;
}
效果图如下: