元素的定位
定位(position)
- 是一种更加高级的布局手段
- 通过定位可以将元素摆放到页面的任意位置
- 使用position属性来设置定位
可选值:
static 默认值,元素是静止的没有开启定位
relative 开启元素的相对定位
absolute 开启元素的绝对定位
fixed 开启元素的固定定位
sticky 开启元素的粘滞定位
相对定位relative
相对定位的特点:
1. 如果设置了相对定位,没有改变偏移量,则元素不会移动
2. 相对的位置是元素所在文档流的位置。
3. 设置了相对定位的元素,不会脱离文档流
4. 设置了相对定位的元素提高了自己的层级
5. 设置了相对定位的元素,本身的性质不会改变, 块依旧是块元素,行内依旧是行内元素
偏移量:
top: 数值是正值,表示向下移动
bottom: 数值是正值,表示向上移动 一般情况下,top和bottom选择一个即可
left: 数值是正值,表示向右移动
right: 数值是正值,表示向左移动 一般情况下,left和right选择一个即可
<head>
<title>Document</title>
<style>
.box1,
.box2,
.box3{
height:300px ;
height: 300px;
}
.box1{
background-color: aqua;
}
.box2{
background-color: red;
/* 开启相对定位,一定要记住,是相对它之前在文档流的位置. */
position: relative;
/* 设置偏移量 */
top: 100px;
left: 100px;
}
.box3{
background-color: pink;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="bo3"></div>
</body>
绝对定位absolute
绝对定位的特点:
1.开启绝对定位后,如果不设置偏移量元素的位置不会发生变化
2.开启绝对定位后,元素会从文档流中脱离
3.绝对定位会改变元素的性质,行内变成块,块的宽高被内容撑开
4.绝对定位会使元素提升一个层级
5.绝对定位元素是相对于其包含块进行定位的
<head>
<style>
.box1,
.box4,
.box3{
width: 200px;
height: 200px;
}
.box1{
background-color: aqua;
}
.box3{
background-color: blueviolet;
}
.box4{
background-color: orange;
/* 因为box2想要相对box4进行绝对定位,因此box2要开启相对定位 */
position: relative;
}
.box5{
width: 150px;
height: 150px;
background-color: pink;
}
.box2{
width: 100px;
height: 100px;
background-color: gray;
/* 开启绝对定位,注意:相对的是它的包含块,包含块必须开启相对定位 */
position: absolute;
left: 50px;
top: 50px;
}
.box3{
width: 400px;
height: 400px;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box4">
<div class="box5">
<div class="box2"></div>
</div>
</div>
<div class="box3"></div>
</body>
固定定位fixed
固定定位也是一种绝对定位,所以固定定位的大部分特点都和绝对定位一样
唯一不同的是固定定位永远参照于浏览器的视口进行定位
固定定位的元素不会随网页的滚动条滚动
<head>
<style>
.box1{
width: 200px;
height: 200px;
background-color: blueviolet;
position: fixed;
left: 100px;
top: 100px;
}
.box2{
width: 200px;
height: 2000px;
background-color:brown;
}
.box3{
width: 200px;
height: 200px;
background-color:chartreuse;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>
粘滞定位sticky
粘滞定位的特点:
1. 粘滞定位的特点和相对定位的特点差不多。
2. 粘滞定位的不同之处,在于当到达某一个固定位置时,粘住不动。
3. 注意:粘滞定位的位置不能超出父元素的范围,否则粘滞效果消失.
<head>
<style>
.box1{
width: 200px;
height: 200px;
background-color: blueviolet;
}
.box2{
width: 200px;
height: 200px;
background-color:brown;
position:sticky;
/* 设置偏移量: 偏移量是相对视口的设置,当元素到达指定位置时,就粘住不动了*/
top: 50px;
left: 200px;
}
.box3{
width: 2000px;
height: 2000px;
background-color:chartreuse;
}
.box11{
width: 400px;
height: 200px;
background-color: palevioletred;
}
.box11,
.box2{
float: left;
}
</style>
</head>
<body>
<div class="box1"></div>
<div class="box11"></div>
<div class="box2"></div>
<div class="box3"></div>
</body>