css 使图片水平垂直居中

css 使图片水平垂直居中

1.利用display:table-cell,具体代码如下:

html代码如下:

1 <div class="img_wrap">
2   <img src="wgs.jpg">
3 </div>

css代码如下:

复制代码

1 .img_wrap{
2     width: 400px;
3     height: 300px;
4     border: 1px dashed #ccc;
5     display: table-cell; //主要是这个属性
6     vertical-align: middle;
7     text-align: center;
8 }

复制代码

效果如下:

img

2.采用背景法:

html代码如下:

1 <div class="img_wrap"></div>

css代码如下:

复制代码

.img_wrap{
    width: 400px;
    height: 300px;
    border: 1px dashed #ccc;
    background: url(wgs.jpg) no-repeat center center;
}

复制代码

效果如下图:

img

3.图片外面用个p标签,通过设置line-height使图片垂直居中:

html代码如下:

1 <div class="img_wrap">
2     <p><img src="wgs.jpg"></p>
3 </div>

css代码如下:

复制代码

 1 *{margin: 0px;padding: 0px}
 2 .img_wrap{
 3     width: 400px;
 4     height: 300px;
 5     border: 1px dashed #ccc;
 6     text-align: center;}
 7 .img_wrap p{
 8     width:400px;
 9     height:300px;
10     line-height:300px;  /* 行高等于高度 */
11 }
12 .img_wrap p img{
13     *margin-top:expression((400 - this.height )/2);  /* CSS表达式用来兼容IE6/IE7 */
14     vertical-align:middle;
15     border:1px solid #ccc;
16 }

复制代码

效果图如下:

img


出处:https://www.cnblogs.com/sese/p/5941389.html

猜你喜欢

转载自blog.csdn.net/example440982/article/details/80224177