css圖片垂直居中

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

1、使用flex實現垂直居中html

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

html代碼:flexbox

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

 css代碼:spa

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

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

給最外層的div設置display屬性爲table;img的父元素div設置display:table-cell,vertical-align: middle;若是你也想實現水平居中,你能夠給最外層的div元素添加text-align: center屬性orm

html代碼:htm

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

 css代碼:blog

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

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

一、給img的父元素添加相對定位屬性(position: relative),同時,要給子元素也就是圖片img元素添加絕對定位屬性(position: absolute)。
二、將圖片元素的top屬性設置爲50%。
三、如今咱們須要給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;}
相關文章
相關標籤/搜索