css 实现水平垂直居中
一、通过设置子元素
.parent{
position: absolute; /* 非static即可 */
width: 500px;
height: 300px;
}
子元素知道 width
, height
-
position
,top
,left
,transform
.child{ width: 100px; height: 50px; position: absolute; top: 50%; left: 50%; transform: translate(-50px, -25px); }
-
position
,left
,right
,top
,bottom
,margin
.child{ positon: absolute; width: 100px; height: 50px; /* 设置 left, right, top, bottom 是为了给marin: auto;的计算定界 */ left: 0; right: 0; top: 0; bottom: 0; margin: auto; }
子元素不知道 width
, height
(子元素的长宽由内容决定)
-
position
,left
,top
,transform
.child{ position: absolute; left: 0; top: 0; transform: translate(-50%, -50%); }
二、通过设置容器
-
flex 布局
.parent{ display: flex; flex-direction: row; justify-content: center; align-items: center; }
-
grid 布局
三、伪元素
vertical-align
- 元素是内联元素才能生效
- 会以容器内最高的元素的中轴进行对齐
.parent{
text-align: center; /* 水平居中 */
width: 500px;
height: 300px;
}
.parent::before{/* 伪元素用于撑开容器的高度,协助vertical-align确定垂直中轴 */
content: "";
display: inline-block; /* vertical-align 要求是内联元素 */
width: 0; /* 宽度为0,不影响其他子元素的布局 */
height: 300px; /* 高度与容器高度相同 */
vertical-align: middle;
}
.child{
display: inline-block; /* vertical-align 要求是内联元素 */
vertical-align: middle;
}