3.层定位layer:网页元素像图层一样 前后层叠在一起 position
网页元素层叠在另一个元素上面:外面的元素父层 里面的式子层
使用position属性设置当前层(网页元素)相对于一层定位(参照物)
static:无定位,文档流,无效z-index
fixed:浏览器窗口(参照物)
relative:这个元素的直接父元素(参照物--直接的自己)
absolute:相对于static的父元素(参照物)
left,right,top,bottom,z-index(前后叠加次序的设定)属性进行位置的定位
比如有一个盒子------------设置了position属性决定了当前盒子的参照物是哪一个
平面关系:那么可以使用top属性设置此盒子距离它参照物上边界的距离
层叠关系:z-index 越大越在上方 大覆盖小 (可以负数)
fixed:浏览器窗口(参照物)--盒子不随下滑线的移动而移动
坐标原点(0,0)左上角--------------------------一般网页上的广告
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页</title>
<style type="text/css">
.box{
width: 200px;
height: 200px;
border: 1px solid red;
position: fixed;
left: 100px;
top: 50px;
}
</style>
</head>
<body>
<div class="box"></div>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
<p>lorem10</p>
</body>
</html>
relative:这个元素的直接父元素(参照物)-------针对自己的父元素,脱离文档流,但是原来的文档流的位置保留,下面的static元素没有去占据位置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页</title>
<style type="text/css">
/*将默认的样式清零*/
*{
padding: 0;
margin: 0;
}
.body{
width: 300px;
height: 600px;
border: 1px solid black;
}
.box{
width: 200px;
height: 200px;
border: 1px solid red;
}
#box1{
background-color: red;
}
#box2{
background-color: green;
position: relative;
top: 200px;
left: 100px;
}
#box3{
background-color: blue;
}
</style>
</head>
<body>
<div class="body">
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
</div>
</body>
</html>
absolute:相对于绝对或者相对的父元素(参照物)--脱离文档流,原来的位置会丢失,下面的static的元素会上去占据它的位置--如果父层没有,则相对于body部分
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>首页</title>
<style type="text/css">
/*将默认的样式清零*/
*{
padding: 0;
margin: 0;
}
.body1{
margin: 100px;
width: 350px;
height: 600px;
border: 1px solid black;
}
.body2{
width: 300px;
height: 600px;
border: 1px solid yellow;
position: relative;
top: 200px;
left: 100px;
}
.box{
width: 200px;
height: 200px;
border: 1px solid red;
}
#box1{
background-color: red;
}
#box2{
background-color: green;
position: absolute;
top: 200px;
left: 100px;
}
#box3{
background-color: blue;
}
</style>
</head>
<body>
<div class="body1">
<div class="body2">
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
</div>
</div>
</body>
</html>
这个可以实现子元素跟随父元素的移动而移动