一、position
position 定义:
position属性指定一个元素(静态的,相对的,绝对或固定)的定位方法的类型。
position 属性:
static:静态定位 (默认),无特殊定位时遵循正常文档流。
relative:相对定位,相对于原位置进行改变。
fixed:固定定位,相较于浏览器窗口,滚动屏幕时它不移动。
absolute:绝对定位,相较于已定位的父元素进行改变,无父元素或父元素无定位时相较于<body>进行改变。
sticky:粘性定位,基于用户滚动的位置,它的位置在相对路径和绝对路径之间转换 。
二、定位属性代码
1、position:static
静态定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#p1{border: 3px solid chartreuse;
position:static;
</style>
</head>
<body>
<p id="p1">这段标签使用静态定位</p>
</body>
</html>
2、position:relative
相对定位不会使周围元素的位置发生改变
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#d1{
border: 0px solid;
height: 100px;
width:300px;
background-color: red;
position:relative;
left: 150px;
}
</style>
</head>
<body>
<div id="d1">
<font>相对定位</font>
</div>
<div id="d2">
</div>
</body>
</html>
3、position:fixed
固定定位
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#p2{
position: fixed;
right: 15px;
}
</style>
</head>
<body>
<P id="p2">固定定位,屏幕滚动时位置不会发生改变</P>
<p>滚动看效果</p><p>Some text</p><p>Some text</p>
<p>Sometext</p><p>Some text</p><p>Some text</p>
<p>Some text</p><p>Some text</p><p>Some text</p>
<p>Some text</p><p>Some text</p><p>Some text</p>
</body>
</html>
4、position:absolute
绝对标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 绝对标签有父元素时 */
#d3{
height: 300px;
width: 700px;
/* 父元素为相对定位 (注掉可查看以<body>为基准的绝对定位*/
position: relative;
background-color: darksalmon;
}
.c1{
border: 0px solid;
height: 50px;
width:100px;
background-color: rgb(217, 255, 0);
position:absolute;
right: 0px;
}
</style>
</head>
<body>
<div id="d3">
<p class="c1">绝对标签</p>
</div>
</body>
</html>
5、position:sticky
粘性标签
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 粘性定位 */
#p3{border: 2px solid rgb(70, 10, 220);
position: sticky;
background-color: rgba(0, 140, 255, 0.815);
top: 0px;
}
</style>
</head>
<body>
<p id="p3">粘性定位</p><br>
</body>
</html>