背景:在项目中常常碰到让元素垂直居中的情形,实现的方法有不少,各有利弊。众所周知的,用flex布局很容易就实现,but,一些不是很主流的浏览器并不支持flex,这就比较尴尬了,有好东西不能在项目中用起来。今天就利用下业余时间,汇总一下经常使用的几种垂直居中的方式。
废话少说,开整。css
如图,若是想让盒子A在盒子B内垂直居中css3
<style> .box { background: gray; height: 100px; width: 200px; } .item { background: pink; height: 20px; width: 100px; } </style> <div class="box"> <div class="item">A</div> </div>
flex方式,兼容到ie10web
.box { display: -webkit-flex; /* 新版本语法: chrome 21+ */ display: flex; /* 新版本语法: opera 12.1, firefox 22+ */ /*flex-direction: row; // 默认水平排列 */ align-items: center; /* 元素排列的垂直方向居中 */ }
利用ifc(行内格式化上下文),其实就是利用行高撑高父元素,视觉上表现也为垂直居中。chrome
.box { line-height: 100px; } .item { display: inline; }
绝对相对定位浏览器
.box { position: relative; } .item { position: absolute; top: 50%; margin-top: -10px; // 自身高度的一半,此用法须要知道自身的高度 // transform: translateY(-50%); // 兼容性容许的话能够用css3特性代替margin-top } // 绝对定位另外一种方式 .item { position: absolute; top: 0; bottom: 0; margin: auto; // left: 0; right: 0; // 这样还能水平居中 }
利用vertical-align,为了避免产生新的dom,可能使用伪类before作辅助,让子元素与伪类垂直居中对齐dom
.box:before { content: ''; height: 100%; vertical-align: middle; display: inline-block; } .item { display: inline-block; }
忽然发现,实现垂直居中的方法有不少,此处先列举几个做参考,若有纰误,欢迎评论指正。如遇到具体状况不知道怎么实现的同窗,也能够私信我,往后也继续完善此贴。布局