css 使圖片水平垂直居中

1.利用display:table-cell,具體代碼以下:css

html代碼以下:html

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

css代碼以下:express

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 }

效果以下:this

 

2.採用背景法:url

html代碼以下:spa

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

css代碼以下:code

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

效果以下圖:htm

 

3.圖片外面用個p標籤,經過設置line-height使圖片垂直居中:blog

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 }

效果圖以下:

相關文章
相關標籤/搜索