绝对定位和相对定位 代码练习(仅供参考)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box1 {
position: relative;
top: 60px;
width: 400px;
height: 400px;
border: 1px solid #000;
background-color: #fff;
}
.box2 {
position: relative;
left: 40px;
width: 300px;
height: 300px;
background-color: orange;
}
.box3 {
position: absolute;
right: 20px;
top: 40px;
width: 100px;
height: 100px;
background-color: #6cf;
}
.box4 {
width: 50px;
height: 50px;
position: absolute;
background-color: #0e0;
right: 40px;
top: 10px;
}
.box5 {
position: absolute;
width: 400px;
height: 400px;
right: 100px;
background-color: #000;
/* z-index: 999; */
}
</style>
</head>
<body>
<!-- 1.相对定位:relative 自己占据位置 不会给其他元素占用 相对于自己占有的原有位置移动 -->
<!-- 2.绝对定位:absolute 脱离标准流, 往上级去找最接近定位元素进行相对移动, 上级可以是绝对定位,也可以是相对定位, -->
<!-- 3.box4 的上级定位元素就是box3(使用了absolute) box4的移动相对于box3的定位 -->
<!-- 4.嵌套包含的关系 box2移动 ,box3和box4作为子级盒子会跟着移动 -->
<!-- CSS中定位方式有static,absolute,fixed,relative,
而使得元素脱离文档标准流的定位方式只有absolute和fixed两种方式。
其它两种方式任然会占有原来的地方。
-->
<!--5. box5 与box1是同层级的关系 box5的定位往上级找定位元素就是body当前页面窗口了,相对于当前的浏览器窗口移动 -->
<!--6 box5 在元素布局排列在box1之前 box5脱离了标准流 会漂浮起来,原有的位置会被box1占用,box1在顶层(用了relative)
如果这时候box5想显示在页面最顶层,可以用z-index:999 就可以反过来把黑色的box1压住了
-->
<div class="box5"></div>
<div class="box1">
<div class="box2">
<div class="box3">
<div class="box4">123</div>
</div>
</div>
</div>
<!-- 总结就是 绝对定位会脱离标准流 往上级找定位元素进行定位移动 相对定位会自己占据原有位置,相对于自己原有的位置移动
同层级均有定位的情况下 用z-index 可以定义页面显示的层级关系
-->
</body>
</html>