跳到主要内容

盒模型对齐

如何用 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, 已不推荐;