css的定位属性为position属性,其作用在于改变元素的位置。position属性的常见属性值有static,fixed,absolute,relative和sticky。
1.第一种定位方式:position:static(静态定位)
static为默认值,没有定位,元素出现于正常的文本流中,无法识别left,right,top及bottom几个方向值。一般不使用该默认的定位值。
2.第二种定位方式:position:fixed(固定定位)
固定定位以整个浏览器窗口为参照物,可以实现元素在浏览器窗口或子元素在父元素里的固定位置。使用了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>
*{
margin: 0;padding: 0;
}
.box{
width: 400px;
height: 300px;
background: pink;
position: fixed;
left: 50%;
top: 50%;
margin: -150px 0 0 -200px;
}
</style>
</head>
<body>
<div class="box"></div>
<p>内容内容内容内容内容内容内容内容内容内容内容内容内容内</p>
</body>
</html>
3.第三种定位方式:position:absolute(绝对定位)
absolute值与fixed值一样使元素脱离文本流、不占据空间。绝对定位以父元素为参照物且父元素必须添加定位,如果父元素没有定位或不存在,则根据整个文档及进行位置的变换。
4.第四种定位方式:position:relative(相对定位)
相对定位不破坏文本流,并且始终占据一定空间。元素以自身为参照物,在原有位置的基础上,识别left,right,top,bottom的规定进行位置移动。当元素根据父元素进行定位时,自身需要添加绝对定位和根据需要加left,right,top,bottom中的规定值;而父元素则添加相对定位position:relative形成参照物。
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>
*{
margin: 0;padding: 0;
}
.header{
width: 1000px;
height: 100px;
background: olivedrab;
margin: 0 auto;
}
.nav{
width: 800px;
height: 70px;
background: orchid;
margin: 0 auto;
position: sticky;
top: 0;
}
.con{
width: 1000px;
height: 2000px;
background: palegreen;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="header"></div>
<div class="nav"></div>
<div class="con"></div>
</body>
</html>