居中布局
水平居中
inline-block + text-align
.parent {
text-align: center;
}
.children {
display: inline-block;
}
text-align会对inline级别的元素生效
table + margin
.children {
display: table;
margin: 0 auto;
}
子元素 display: table, table 在没有设置宽度的时候,跟里面的内容的宽度是一样的。
table 还可以使用 margin: auto,因此可以实现水平居中。
absolute + transform
.parent {
position: relative;
}
.children {
position: absolute;
left: 50%;
transform: translateX(-50%);
}
flex + justify + content
.parent {
display: flex;
justify-content: center;
}
flex-item 的默认样式是 1
或
.parent {
display: flex;
}
.children {
margin: 0 auto;
}
垂直居中
tabel-cell + vertical-align
.parent {
display: table-cell;
vertical-align: middle;
}
tabel-cell 会把子元素放在垂直中间,
vertical-align: middle 再把内容居中
absolute + transform
.parent {
position: relative;
}
.children {
position: absolute;
top: 50%;
transform: translateY(-50%);
}
flex + align-items
.parent {
display: flex;
align-items: center;
}
居中
inline-block + text-align + tabel-cell + vertical-align
.parent {
text-align: center;
display: table-cell;
vertical-align: middle;
}
.children {
display: inline-block;
}
absolute + transform
.parent {
position: relative;
}
.children {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
flex + justify-content + align-items
.parent {
display: flex;
justify-content: center;
align-items: center;
}