根据不一样状况,使用的垂直居中方式各异:针对块级元素与行级元素的垂直居中不一样。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%) }