根據不一樣狀況,使用的垂直居中方式各異:針對塊級元素與行級元素的垂直居中不一樣。css
若是行內包含特殊元素:圖片、input
輸入框、inline-block
元素或者粗體佈局
使用verticle-align: middle;
設置對齊方式便可垂直居中。text-bottom/text-top 爲下對齊/上對齊
post
兼容性很好:IE4flex
line-height
設置line-height
與height
值相等,能夠實現行級元素或者純文本的塊級元素的垂直居中code
兼容性好IE4orm
flex
和align-items
設置容器元素display: flex; align-items: center;
便可,其內的子元素在容器中垂直居中繼承
缺點: 使用flex
佈局,而且使用CSS3的align-items
屬性,兼容性較差:IE11圖片
flex
和align-self
設置容器元素display: flex;
,子元素設置align-self: center;
input
align-self
屬性容許單個項目有與其餘項目不同的對齊方式,可覆蓋align-items
屬性。默認值爲auto
,表示繼承父元素的align-items
屬性,若是沒有父元素,則等同於stretch
it
一樣兼容性較差:IE11
父元素設置相對定位position: relative;
子元素設置絕對定位postion: absolute; top: 0; left:0; bottom: 0; right: 0; margin: auto;
關鍵在於設置top: 0; left:0; bottom: 0; right: 0; margin: auto
表示水平、垂直4個方向的margin
值都經過計算獲取
兼容性IE7
<div class="wrap"> <div class="child"></div> </div> <style type="text/css"> * {margin: 0; padding: 0;} .wrap {position: relative; 100vw; height: 100vh;} /* 注意清除margin和padding,不然100vh不對*/ .child { position: absolute; top: 0; bottom: 0; right: 0; left: 0; margin: auto; width: 200px; height: 100px; background: lightgreen; }
display: table-cell
表格元素能夠設置verticle-align: middle;
實現垂直居中
爲容器添加display: table-cell; verticle-align: middle;
缺點是不能設置百分比寬度,能夠設置固定像素值
兼容向IE8
利用父元素相對定位,子元素絕對定位,而且處置、水平方向個偏移50%
子元素利用負值margin
偏移自身寬度、長度的一半
缺點是須要固定子元素的寬高
兼容性IE7
translate()
屬性position: absolute; top: 50%; left: 50%;
中,50%
是相對容器的寬度
transform: translate(-50%, 50%)
是相對於元素自身的寬度,無需再用負的margin
值
父元素設置{ position: relative; } 子元素設置{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, 50%) }