垂直居中元素(如何让它水平且垂直居中的六种方法)(1)

这类问题是面试中经常出现的css问题。那么你会吗?会的话,你能想出几种解决方案呢?我这里大致列举六个方法!

分享之前推荐下我的前端群:524262608,不管你是小白还是大牛,小编我都挺欢迎,不定期分享干货,包括我自己整理的一份2017最新的前端资料和零基础入门教程,欢迎初学和进阶中的小伙伴。

1.弹性盒模型flex布局

<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; display: flex; justify-content: center; /*主轴居中对齐*/ align-items: center; /*交叉轴即y方向剧中对齐*/ } .box{ width: 333px; height: 333px; background: blue; }</style></head><body> <div class="wrap"> <div class="box"></div> </div></body>

2.利用伪类来对齐

<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; text-align: center; } .wrap:after{ display: inline-block; content: ''; height: 100%; /*width:0;*/ vertical-align: middle; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; vertical-align: middle; }</style></head><body> <div class="wrap"> <div class="box"></div> </div></body>

3.利用空span,原理与上面的类似

<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; text-align: center; } span{ display: inline-block; height: 100%; vertical-align: middle; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; vertical-align: middle; }</style></head><body> <div class="wrap"> <div class="box"></div><span></span> </div></body>

4.利用表格的特性:单元表格的内容默认垂直居中

<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; text-align: center; border-collapse: collapse; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; /*margin: 0 auto;*/ /*或者*/ }</style></head><body> <table class="wrap"> <td><div class="box"></div></td> </table></body>

5.将块标签转换成表格属性,display:table-cell

<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; display: table-cell; text-align: center; vertical-align: middle; } .box{ width: 333px; height: 333px; background: blue; display: inline-block; vertical-align: middle; }</style></head><body> <div class="wrap"> <div class="box"></div> </div></body>

6.利用相对定位和transform

<style type="text/css"> .wrap{ width:500px; height: 500px; background: red; /*display: table-cell;*/ /*text-align: center;*/ } .box{ width: 333px; height: 333px; background: blue; position: relative;//不脱离文档流,left,top移动父级的百分之五十 left: 50%; top: 50%; -webkit-transform: translateX(-50%) translateY(-50%)//即使未知元素自身宽高,自动计算后x,y轴移动元素自身宽高的负百分之五十 }</style></head><body> <div class="wrap"> <div class="box"></div> </div></body>

总结:span和伪类对齐方法主要是利用了空内容将基线定在了父级元素的中间位置,然后用inline-block结合vertical-align:middle. table的2种方法则是利用了表格的自带属性,弹性盒模型的话就不用多说了,强大的爱不释手,

最后还是要推荐下我的前端群:524262608,不管你是小白还是大牛,小编我都挺欢迎,不定期分享干货,包括我自己整理的一份2017最新的前端资料和零基础入门教程,欢迎初学和进阶中的小伙伴。

transform和相对定位结合处理的话,因为要依据父级宽高所以用相对定位,用绝对定位的话会一层层找到顶级,transform再根据自身宽高负方向移动半个宽高。

web前端学习方法经验可以关注我的‘学习web前端’,每天更新案例源码或经验分享,关注后回复‘给我资料’可以领取一套完整的学习视频

,