css中position属性详解

css中position属性详解

在CSS中关于定位的内容是:position:static ,relative , absolute , fixed ,sticky

static 默认值,自动定位,文档流中的位置,自动定位就是元素在页面普通文档流中由HTML自动定位。

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>

在这里插入图片描述

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>

在这里插入图片描述
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>

在这里插入图片描述
• **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>

在这里插入图片描述
在这里插入图片描述

发布了87 篇原创文章 · 获赞 198 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/low666/article/details/104643278