设置块级父元素 text-align 为 center
See the Pen inline-element-align-center by Wen Yongyang (@monsoir) on CodePen.
margin-left, margin-right 为 auto, 原理:
margin 不为具体的数字时,是根据父元素的宽度进行计算的margin-left 设置为 auto 时,左外边距为元素占据父元素后剩下的长度margin-right 同理于 margin-leftmargin-left 与 margin-right 都为 auto 时,左右外边距就会平均分父元素剩下的长度,达到水平居中的效果See the Pen MxEVQK by Wen Yongyang (@monsoir) on CodePen.
确定文本不超过一行的,设置元素的上下内边距(padding-top, padding-bottom)为相同值
下面例子垂直居中的目标是红色区域的文字
See the Pen ZPXoze by Wen Yongyang (@monsoir) on CodePen.
父元素设置了
padding是为了防止子元素由于设置了padding而导致了部分超出范围不可视的问题
当方法一的方式方式不起作用时,可以将设置 line-height 与 height 相等,但需要保证文本不超过一行
下面例子垂直居中的目标是红色区域的文字
See the Pen block-element-align-center-vertically-2 by Wen Yongyang (@monsoir) on CodePen.
同样可以设置元素的上下内边距(padding-top, padding-bottom)为相同值
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
使用 <table>, 其单元格默认垂直居中
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
构建类似 <table> 的布局
display 为 tabledisplay 为 table-cellvertical-align 为 middle, 这是与直接设置 <table> 标签不同的地方See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
使用 Flexbox 布局
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
使用伪元素,又称幽灵元素
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
思路在于
position 设置为 absolute 时,top 设置为百分比时,计算的参照对象为父元素See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
思路与已知高度时大致相同
translateY 移动目标元素的垂直位置
translate 函数中的参数若为百分比,则计算的参照物为元素自身的大小See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
使用 Flexbox 进行垂直居中布局非常简单,甚至只需要设置父元素的样式即可
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
实现思路
由于已知宽高,可以使用绝对定位将目标元素在父元素范围内,将 top 与 left 便宜 50%, 再使用具体数值的负外边距,margin-left, margin-top 来调整位置
若目标元素含有内边距,则还需要将内边距纳入调整距离的计算
下面例子,居中的元素为粉红色区域,上面的文字只是告知这个区域含有内边距
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
与「已知宽高」的方法大致相同,但调整距离的方式是使用 translate 方法
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.
是最简单的方法,即使用 Flexbox 布局
只需要设置三个 CSS 属性
display: flex;
justify-content: center;
align-items: center;
See the Pen rRGreO by Wen Yongyang (@monsoir) on CodePen.