1. 程式人生 > >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 }
複製程式碼

效果如下:

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;
}
複製程式碼

效果如下圖:

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 }
複製程式碼

效果圖如下: