css中position属性详解
在CSS中关于定位的内容是:position:static ,relative , absolute , fixed ,sticky, inherit
1.position:static
默认值,自动定位,文档流中的位置,自动定位就是元素在页面普通文档流中由HTML自动定位。
2.position:absolute
绝对定位,绝对定位脱离文档流,依据最近的已经定位(绝对、相对或固定定位)的父元素,通过 top,bottom,left,right 定位。当父级 position 为 static 时,absolute元素将依据body根元素(浏览器窗口)进行定 位,可以通过z-index进行层次分级。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 100px;
width:200px;
background-color: blue;
opacity: 0.5;
}
.ab{
position: absolute;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab" >2</div>
</body>
</html>
3.position:relative
相对定位,相对定位不脱离文档流,参考其在原来文档流中的位置,通过 top,bottom,left,right 定位,并 且可以通过z-index进行层次分级。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 100px;
width:200px;
background-color: blue;
opacity: 0.5;
}
.ab{
position: relative;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab" >2</div>
<div>3</div>
</body>
</html>
4.position:fixed
固定定位,固定定位与父元素无关(无论父元素是否定位),直接根据浏览器窗口定位,且不随滚动条拖动 页面而滚动,可通过z-index进行层次分级。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 100px;
width:200px;
background-color: blue;
opacity: 0.5;
}
.ab{
position: fixed;
left: 50px;
top: 50px;
background-color: pink;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab" >2</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
</body>
</html>
5.position:sticky:
position: sticky; 基于用户的滚动位置来定位。
粘性定位的元素是依赖于用户的滚动,在 position:relative 与 position:fixed 定位之间切换。
它的行为就像 position:relative; 而当页面滚动超出目标区域时,它的表现就像position:fixed;,它会固定在目标位置。
元素定位表现为在跨越特定阈值前为相对定位,之后为固定定位。
这个特定阈值指的是 top, right, bottom 或 left 之一,换言之,指定 top, right, bottom 或 left 四个阈值其中之一,才可使粘性定位生效。否则其行为与相对定位相同。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>position/position</title>
<style type="text/css">
div{
height: 90px;
width: 200px;
background-color: pink;
opacity: 0.5;
}
.ab{
height: 90px;
width: 200px;
background-color: blue;
opacity: 0.5;
position: sticky;
top:0;
margin-top:20px;
}
</style>
</head>
<body>
<div>1</div>
<div class="ab">2</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
<div>3</div>
</body>
</html>
6.position: inherit
w3school.com的 描述
规定应该从父元素继承 position 属性的值。
inherit 继承父元素,这个用得不多,所以也不继续深入了。