CSS实现垂直居中的八种方式(全)

垂直居中的实现是一个老生常谈的问题了,不管是面试还是日常的工作中,总是会遇到类似的效果实现。
这里总结了八种简单常用不定宽高的实现方式分享给大家。

问题描述:实现在父元素“class = father”中实现“class = son”的垂直居中

1、使用flex布局,只对父元素设置

.father{ display:flex; justify-content:center; align-items:center; }

2、flex布局+margin:

.father{ display: flex; }

.son{ margin: auto; }

3、gird布局

.father{ display: grid; }

.son{ justify-self:center; align-self:center; }

4、gird布局+margin

.father{ display: grid; }

.son{ margin:auto; }

5、子绝对定位 父相对定位

.father{ position: relative; }

.son{ position:absolute; left:0; right:0; top:0; bottom:0; margin:auto; }

6、父元素相对定位,子元素通过transform像左上偏移

.father{ position: relative; }

.son{ position:absolute; left:50%; top:50%; transform: translate(-50%,-50%); }

7、通过display:table-cell

.father{ display:table-cell; vertical-align:middle; text-align:center; }

.son{ display:inline-block; }

8、和方法2比较类似,不过注意这里是通过align-self设置垂直居中,通过margin:0 auto设置水平居中。

.father{ display:flex; }

.son{ align-self: center; margin: auto; }

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享