一.position属性
- 对当前标签对象进行定位操作,属性规定元素的定位类型
- 取值范围: 静态(static),相对(relative),绝对(absolute)、固定(fixed)
- css四个属性(top、left、right、bottom)只有在设置了position值为relative、absolute、fixed情况下才有效
二.relative(相对定位)
- 格式说明:position:relative
- 相对定位特点:
①. 通过top、left、bottom、right来设置元素的新位置偏移(相对于当前位置)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Title</title>
<style type="text/css">
.box1,.box2{
width: 100px;
height: 100px;
position: relative;
}
.box1{
background-color: red;
top: 10px;
z-index: 1;
}
.box2{
margin-left: 10px;
background-color: #0000FF;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
三.fix(固定定位)
- 格式说明:position:fixed
- 固定定位特点:
- 通过top、left、bottom、right来设置元素的新位置偏移(相对于浏览器视窗)
- 固对定位的元素脱离标准文档流,不受文档流约束
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.bg1{
background-color: red;
}
.bg2{
background-color: #6c5d4c;
}
.bg3{
background-color: yellow;
}
.bg{
height: 500px;
position: relative;
}
.fixBox{
position: fixed;
z-index: 1;
top: 10px;
left: 20px;
width: 100px;
height: 400px;
background-color: lightgray;
}
</style>
</head>
<body>
<div class="fixBox">固定的面板</div>
<div class="bg bg1">
</div>
<div class="bg bg2">
</div>
<div class="bg bg3">
</div>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
四.absolute(绝对定位)
- 格式说明:
position:absolute
; - 绝对定位特点
- 通过top、left、bottom、right来设置元素的新位置偏移
- 相对定位的元素脱离标准文档流
案例:
- 未使用绝对定位两个div布局如下
- 当红色div使用绝对定位后,蓝色占据原来红色div的位置( 因为相对定位的元素脱离标准文档流)代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.box1,.box2{
width: 100px;
height: 100px;
}
.box1{
position: absolute;
top: 50px;
left: 50px;
background-color: red;
}
.box2{
background-color: #0000FF;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
</body>
</html>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
五.定位参考点
- 如果绝对定位盒子外层没有盒子
- top:以距离页面顶部具体top长度显示
- bottom:以距离当前浏览器底部bottom值显示
- 如果绝对定位盒子外层还有盒子
- 默认相对于浏览器绝对定位偏移
- 如果要相对父容器绝对定位,则要遵循如下规则:父元素必须要有定位(绝、相、固)设置
六.z-index定义
- 属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺- 序较低的元素的前面(默认为0)
- z-index只有在当前元素设置了position的时候才有效
- 特性:
- 随父性:父元素的z-index值,会影响子元素的重叠效果
本文转载自:https://blog.csdn.net/asd245025733/article/details/70537057