盒模型对齐
如何用 margin auto 实现左右对齐?
- 前提: 元素有确定 width;
- 右对齐:
margin-left: auto; - 左对齐:
margin-right: auto;
.right {
width: 200px;
margin-left: auto;
}
水平垂直居中有哪些方案?
- flex: 容器
display: flex+align-items: center+justify-content: center; - 文本: 容器固定
line-height等于height, 再加text-align: center; - 绝对定位 + margin auto: 父
relative, 子absolute且四向为 0, 再margin: auto;
.container {
display: flex;
align-items: center;
justify-content: center;
}
.son {
position: absolute;
inset: 0;
margin: auto;
width: 100px;
height: 40px;
}
- 绝对定位 + 负边距: 子元素
top: 50%、left: 50%, 再用宽高一半的负 margin 拉回; - table 布局:
display: table+table-cell, 已不推荐;