1.水平方向居中:margin:0 auto;此时要记得设置宽度,设置了宽度之后auto才能平分剩下的宽度,从而实现居中.
2.垂直方向居中:margin:auto 0;无效,因为垂直方向没有剩余空间这种概念.
如图,设置无效.
3.垂直水平方向都居中:
①设置绝对定位和四个方向为0,margin:auto
(单独设置top和left任意两个方向都不行)
div{
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
margin: auto;
height: 200px;
width: 200px;
background: red;
}
②设置父盒子为flex,子盒子margin:auto
.father {
display: flex;
width: 100%;
height: 100%;
background-color: purple;
}
.son {
height: 50%;
width: 50%;
margin: auto;
background-color: red;
}
- 定位是相对于离元素最近的设置了绝对或相对定位的父元素决定的.
- 如果没有父元素设置绝对或相对定位,则元素相对于根元素即html元素定位。
- 设置了absolute的元素脱离了文档流,元素在没有设置宽度的情况下,宽度由元素里面的内容决定.
- 脱离后原来的位置相当于是空的,下面的元素会来占据位置。