1.水平与垂直居中
- flex布局,父元素
display: flex;
justify-content: center; // 水平居中
align-items: center; // 垂直居中
- 子元素相对父元素绝对定位,加上transform
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%)
- 子元素相对父元素绝对定位,加上margin负值
position: absolute;
top: 50%;
left: 50%;
margin-top: -子元素高度一半
margin-left: -子元素宽度一半
- 子绝父相,子的上下左右全为0,再加上margin:auto
// 父元素
position: relative;
// 子元素
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
top和bottom为0是设置垂直居中的,left和right是水平居中的。
2.水平居中
- 父子元素宽度固定,子元素margin:auto,并且子元素不能设置浮动。
- 父子元素宽度固定,父:text-align: center,子元素display:inline-block
3.垂直居中
- 行内元素:设置子元素行高和父元素高度一样