css圖片垂直居中


轉載文章出處和來源網址:http://www.thinkcss.com/jiqiao/1492.shtml

一、使用flex實現垂直居中

利用  display: flex;align-items: center   實現垂直居中。flex可能不是實現垂直居中最好的選擇,因為IE8,9並不支持它。

html代碼:

<div class="flexbox">
    <img src="1.jpg" alt="">
</div>

 css代碼:

body{ background:#999}
.flexbox{width: 300px;height: 250px;background:#fff;display: flex;align-items: center}
.flexbox img{width: 100px;height: 100px;align-items: center;}

二、利用Display: table;實現img圖片垂直居中

給最外層的div設置display屬性為table;img的父元素div設置display:table-cell,vertical-align: middle;如果你也想實現水平居中,你可以給最外層的div元素添加text-align: center屬性

html代碼:

<div class="tablebox">
    <div id="imgbox">
        <img src="1.jpg" alt="">
    </div>
</div>    

 css代碼:

.tablebox{width: 300px;height: 250px;background: #fff;display: table}
#imgbox{display: table-cell;vertical-align: middle;}
#imgbox img{width: 100px}

三、用絕對定位實現垂直居中(推薦-兼容性好)

1、給img的父元素添加相對定位屬性(position: relative),同時,要給子元素也就是圖片img元素添加絕對定位屬性(position: absolute)。
2、將圖片元素的top屬性設置為50%。
3、現在我們需要給img元素設置一個負的margin-top值,這個值為你想要實現垂直居中的元素高度的一半,*如果不確定元素的高度,可以不使用margin-top,而是使用transform:translateY(-50%);屬性。
記住:如果你想要同時實現水平居中,那么你可以用實現垂直居中的一樣的技巧來實現。

HTML代碼:

<div class="posdiv">
    <img src="1.jpg" alt="">
</div>

css代碼:

body{background: #ccc;}
.posdiv{width: 300px;height: 250px;background: #fff;position: relative; margin:0 auto}
.posdiv img{width: 100px;position: absolute;top: 50%;margin-top: -50px;}

 


免責聲明!

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



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