绝对定位absolute
绝对定位的参考物是:距离最近的使用了定位的父级,父级都没有使用时找body
绝对定位的特点:
元素脱离文档流
行元素支持所有的css样式
块元素由内容撑开宽高
清除子级浮动
div{
width: 100px;
height: 100px;
margin-bottom: 10px;
font-size: 40px;
text-align: center;
line-height: 100px;
background-color: orange;
}
div:nth-of-type(2){
position: absolute;
left: 100px;
}
<div>1</div>
<div>2</div>
<div>3</div>
.one{
background-color: orange;
width: 300px;
height: 300px;
position: relative;
}
.two{
background-color: greenyellow;
width: 200px;
height: 200px;
position: absolute;
top: 50px;
left: 50px;
}
.three{
background-color: skyblue;
width: 100px;
height: 100px;
position: absolute;
top: 50px;
left: 50px;
}
<div class="one">
<div class="two">
<div class="three"></div>
</div>
</div>
使用定位实现万能居中:
.background{
width: 100vw;
height: 100vh;
background-color: rgba(0, 0, 0, .7);
}
.background div{
width: 300px;
height: 200px;
background-color: #fff;
/* 以下代码实现万能居中 */
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -100px;
}
<div class="background">
<div>
万能居中公式:<br>
position: absolute;<br>
left: 50%;<br>
top: 50%;<br>
margin-left: -width/2;<br>
margin-top: -height/2;<br>
</div>
</div>