水平居中
- 行内元素, 父级是块级, 设置 text-align: center;
- 块级元素, 宽度确定, margin: 0 auto;
- 块级元素, 宽度不确定, display: inline-block 或 display: inline 其转换成行内块级, 再套用 1
- 块级元素, 使用 绝对定位 position:absolute, left:50%, 然后 margin-left: -宽度的一半px; 或者transform: translateX(-50%)
- flex布局, 父元素添加属性 display: flex; justify-content: center;
垂直居中
- 行高等于盒子的高, line-height === height
- 行内元素 vertical-align: middle
- 块级元素, 使用 绝对定位 position:absolute, top:50%, 然后 margin-top: -宽度的一半px; 或者transform: translateY(-50%)
- flex布局, 父元素添加属性 display: flex; align-items: center;
水平垂直居中
- 父元素为非static,给子元素设置绝对定位,top: 0; right: 0; bottom: 0; left: 0; margin: auto;
- 绝对定位,left: 50%; top: 50%; margin-left: --元素宽度的一半px; margin-top: --元素高度的一半px;
- flex布局, 父元素添加属性 display: flex; justify-content: center;align-items: center;
双飞翼
左右固定, 中间自适应
- 浮动
- 绝对定位, main left和right等值
- flex
- table
- calc()+inline-block
- grid