html
<div class="parent">
<div class="child child1"></div>
<div class="child child2"></div>
<div class="child child3"></div>
<div class="child child4"></div>
</div>
css
.child {
width: 100px;
height: 100px;
}
.child1{
background: green;
}
.child2{
background: orange;
}
.child3{
background: blue;
}
.child4{
background: yellow;
}
没有设置position的布局
position:static、relative、fixed、absolute
position:static
正常文档流,与不设置position相同,top,right,left,bottom设置后不起作用
position:relative
遵循正常文档流,可以设置top,right,left,bottom,并且这些偏移是相对自己的。设置relative后,不会影响其它元素的位置
将child2设置position:relative
.child2{
background: orange;
position: relative;
top:30px;
left:30px;
}
页面布局
可以设置z-index值改变层叠关系
css
.child2{
background: orange;
position: relative;
top:30px;
left:30px;
z-index:-1;
}
设置z-index后页面布局
position:absolute
脱离正常文档流,所以它的位置会由下面的元素顶替,可以设置top、left、bottom、right,并且位置是相对于离他最近的父级以上的直系祖先的非static的元素,如果找不到就以html作为原点进行偏移
css
.child3{
background: blue;
position: absolute;
left:100px;
top:100px;
}
设置后的布局
同样absolute可以设置z-index值
position:fixed
脱离文档流,基本和absolute相同,但是它相对的是窗口进行偏移
同样可以设置z-index值