position 属性指定了元素的定位类型。
position 属性的五个值:
1.static
2.relative
3.fixed
4.absolute
5.sticky
1.static定位
HTML 元素的默认值,即没有定位,遵循正常的文档流对象。
静态定位的元素不会受到 top, bottom, left, right影响。
就是说,即使你添加了top,left,right,bottom属性。也不会作用到元素。
.static{
width: 150px;
height: 150px;
background-color: lawngreen;
position: static;
line-height: 150px;
top: 150px;/*无效*/
left: 150px;/*无效*/
}
2.relative定位
元素的定位是相对其正常位置。
.relative{
width: 500px;
height: 500px;
background-color: chocolate;
position: relative;
top: 15px;
line-height: 500px
}
3.fixed定位
元素的位置相对于浏览器窗口是固定位置。
即使窗口是滚动的它也不会移动:
.fixed{
width: 150px;
height: 150px;
background-color: brown;
position: fixed;
bottom: 15px;
right: 15px;
line-height: 150px
}
4. absolute定位
绝对定位的元素的位置相对于最近的已定位父元素(父元素的定位方式可以是relative,absolute,fxied),
如果元素没有已定位的父元素,那么它的位置相对于<html>:
.absolute{
width: 150px;
height: 150px;
background-color: brown;
position: absolute;
bottom: 250px;
right: 15px;
line-height: 150px
}
5.sticky 定位
position: sticky; 基于用户的滚动位置来定位。
粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。
它的行为就像 position:relative; 而当页面滚动超出目标区域时,
它的表现就像 position:fixed;,它会固定在目标位置。
元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。
这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,
指定 top, right, bottom 或 left 四个阈值其中之一,才可
使粘性定位生效。否则其行为与相对定位相同。
可以通过运行和修改以下代码详细研究各种定位的作用和区别
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
body{
padding: 0;
margin: 0;
text-align: center;
height: 1900px;
}
.fixed{
width: 150px;
height: 150px;
background-color: brown;
position: fixed;
bottom: 15px;
right: 15px;
line-height: 150px
}
.absolute{
width: 150px;
height: 150px;
background-color: brown;
position: absolute;
bottom: 250px;
right: 15px;
line-height: 150px
}
.relative{
width: 500px;
height: 500px;
background-color: chocolate;
position: relative;
top: 15px;
line-height: 500px
}
.static{
width: 150px;
height: 150px;
background-color: lawngreen;
position: static;
line-height: 150px;
top: 150px; /*无效*/
left: 150px;
}
.sticky{
width: 100%;
height: 55px;
background-color: lightseagreen;
position: sticky;
top: 0;
line-height: 55px;
}
</style>
<body>
<div class="static">
static
</div>
<div class="sticky">
sticky
</div>
<div class="fixed">
fixed
</div>
<div class="relative">
relative
<div class="absolute">
absolute
</div>
</div>
</body>
</html>