一个div的分层
文字内容(内联子元素)> 浮动元素 > 块级子元素 > border > background
浮动内容是比正常的div要高一点的
position
- static默认值,待在文档流里
- relative相对定位,升起来,但不脱离文档流
- absolute绝对定位,定位基准是祖先里的非static
- fixed固定定位,定位基准是viewpoint
- sticky粘滞定位
黑色视角来看,绿色其实还在它原来的位置:
后来居上,如果绿色想压过黑色,需要加上z-index:1,每个元素z-index默认为auto:
- z-index:auto默认值,不创建新层叠上下文
- white-space:nowrap; 文字内容不准换行
- absolute相对于祖先元素中最近的一个定位元素定位,position不是static就是定位元素
<!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>
.container {
border: 1px solid red;
height: 300px;
position: relative;
padding: 20px;
}
* {
box-sizing: border-box;
}
.clearfix::after {
content: '';
clear: both;
display: block;
}
.demo {
border: 1px solid green;
background: green;
width: 50px;
height: 50px;
position: relative;
z-index: 0;
top: 5px;
}
.demo2 {
background: black;
width: 50px;
height: 50px;
position: relative;
z-index: -1;
}
.close {
position: absolute;
top: 0;
right: 0;
padding: 0 8px;
background: blue;
color: white;
}
/* 鼠标悬浮显示提示内容 */
button {
position: relative;
}
button span {
position: absolute;
border: 1px solid red;
white-space: nowrap;
bottom: calc(100% + 10px);
left: 50%;
transform: translateX(-50%)
}
button span {
display: none;
}
button:hover span {
display: inline-block;
}
</style>
</head>
<body>
<div class="container clearfix">
<div class="demo"></div>
<div class="demo2"></div>
<div style="height: 100px;"></div>
<span class="close">X</span>
<button>点击<span class="tips">提示内容</span></button>
</div>
</body>
</html>
- position:fixed; 手机上尽量不要用这个属性,坑很多
- 视口:网页能够给用户看到的区域,在屏幕上显示的区域
层叠上下文
- 每一个层叠上下文就是一个新的作用域
- 这个作用域里面的z-index跟外界无关
- 处在同一个作用域的z-index才能比较
哪些属性可以创捷层叠上下文?
- z-index:0;
- 处在flex里面;
- opacity不为1;
- 有transform;
负z-index与层叠上下文?
- 负z-index逃不出作用域
背景色只影响背景色,opacity影响所有东西
资料来源:饥人谷