relative和absolute的关系
限制作用
- 限制left/top/right/bottom定位;(这一点大家开发肯定都很熟悉了)
- 限制z-index层级;
- 限制在overflow下的嚣张气焰;
对于第2点,上代码演示:
<!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>
.green {
width: 100px;
height: 100px;
background-color: green;
z-index: 3;
position: absolute;
}
.red {
width: 100px;
height: 100px;
background-color: red;
z-index: 2;
position: absolute;
}
</style>
</head>
<body>
<div class="green"></div>
<div class="red"></div>
</body>
</html>
效果如下图,此时z-index越大,层级最高
但是,若是外层套上div元素,position设为relative,且设置的是具体的数值(不包括auto,z-index为auto不会新建层叠上下文)。属性为position:relative的元素z-index的大小决定层级高低。
<!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>
.green {
width: 100px;
height: 100px;
background-color: green;
z-index: 3;
position: absolute;
}
.red {
width: 100px;
height: 100px;
background-color: red;
z-index: 2;
position: absolute;
}
.relative1 {
position: relative;
z-index: 2;
}
.relative2 {
position: relative;
z-index: 3;
}
</style>
</head>
<body>
<div class="relative1">
<div class="green"></div>
</div>
<div class="relative2">
<div class="red"></div>
</div>
</body>
</html>
relative的最小化影响原则
- 尽量避免使用relative
- relative最小化
<!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>
img {
width: 100px;
height: 100px;
}
</style>
</head>
<body>
<div>
<div>111</div>
<div style="position: relative;">
<img
src="https://tse3-mm.cn.bing.net/th/id/OIP-C.jyWYITfTnZ3tIelmbMj_cAHaNC?w=188&h=331&c=7&o=5&dpr=1.25&pid=1.7"
style="position: absolute;top: 0;right: 0;"
>
</div>
<div>111</div>
</div>
</body>
</html>
以上的理解可能有偏差,欢迎大家留意指正