未知寬高的圖片水平垂直居中的幾種方法


最近在項目中遇到不固定寬高的圖片要水平垂直居中的情況,發現垂直居中存在兼容性問題,下面收集了一些方法,可根據需要權衡使用。

 

1. 背景法(兼容性好,簡單,但不利於動態導入的圖片)

 

html:

<div class="wrap"></div>

css:

.wrap{
    width:300px;
    height:200px;
    background: url(../img/test.jpg) center center no-repeat;
}

 

2. 圖片外面用個p標簽,通過設置line-height使圖片垂直居中(兼容性較好)

 

html:

<div class="wrap">
    <img src="./img/test.jpg">
</div>

css:

.wrap{
    width: 300px;
    height: 300px;
    border: 1px solid #000;
    text-align: center;
}
.wrap p{
    width: 300px;
    height: 300px;
    line-height: 300px;
}
.wrap p img{
    *margin-top:expression((300 - this.height )/2);
    vertical-align: middle;
}        

 

3. 利用display:table-cell(不兼容IE6、7)

 

html:

<div class="wrap">
    <img src="./img/test.jpg">
</div>

css:

.wrap{
    width: 300px;
    height: 200px;
    border: 1px dashed #ccc;
    display: table-cell; 
    vertical-align: middle;
    text-align: center;
}

 

4. 添加table標簽(兼容性好,但是冗余標簽比較多)

 

html:

<div class="wrap">
    <table>
        <tr>
            <td align="center"><img src="./img/test.jpg"/></td>
        </tr>
    </table>
</div>

css:

.wrap{
    width: 300px;
    height: 200px;
    border: 1px dashed #ccc;
    text-align: center;
}
.wrap table{
    width: 300px;
    height: 200px;
}   

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM