水平居中
内联
text-align: center
块级
margin
margin: 0 auto
margin 值为 auto 会吸收该维度中所有的可用空间,因此通过为块设置左右自动边距可以将其居中
inline-block
.parent {
text-align: center;
}
.child {
display: inline-block;
}
flex 布局
.parent {
display: flex;
justify-content: center;
}
grid 布局
.parent {
display: grid;
justify-content: center;
}
固定宽度(定位 + margin 负边距)
.parent {
position: relative;
}
.child {
position: absolute;
width: 100px;
left: 50%;
margin-left: -50px;
}
固定宽度(定位 + margin 自适应)
.parent {
position: relative;
}
.child {
position: absolute;
width: 100px;
left: 0;
right: 0;
margin: 0 auto;
}
不定宽度(定位 + transform)
.parent {
position: relative;
}
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
垂直居中
单行内联
设置内联元素的高度 height 和行高 line-height 相等
.parent {
height: 100px;
line-height: 100px;
}
适合文字居中且高度固定的场景
多个
表格布局
.parent {
display: table;
height: 100px;
}
.child {
display: table-cell;
vertical-align: middle;
}
vertical-align 属性主要作用于行内元素和单元格 (table-cell) 元素, 在块级元素中不会生效。这是因为块级元素默认会占据其父容器的整行, 不存在垂直对齐的概念。
flex 布局
.parent {
display: flex;
align-items: center;
}
grid 布局
.parent {
display: grid;
align-content: center;
}
块级
固定宽度(定位 + margin 负边距)
类似上面的水平居中
固定宽度(定位 + margin 自适应)
类似上面的水平居中
不定宽度(定位 + transform)
类似上面的水平居中
图片垂直居中
.parent {
height: 100px;
line-height: 100px;
font-size: 0;
}
.child {
width: 50px;
height: 50px;
vertical-align: middle;
}