天天看点

position的值, relative和absolute分别是相对于谁进行定位,你真的知道吗?

常见的position定位方式如下:

  • static 默认值。元素出现在正常的普通流中
  • relative 生成相对定位的元素,相对于其在普通流中的位置进行偏移。
  • fixed (老IE不支持)生成绝对定位的元素,通常相对于浏览器窗口或 iframe 进行定位。
  • inherit 继承父元素的position属性,但需要注意的是IE8以及往前的版本都不支持inherit属性。
  • absolute 生成绝对定位的元素, 相对于最近一级的 不是 static 的父元素来进行定位,如果没有找到的话,最终是根据body进行定位。

    注意:

    absolute定位的基准是相对于最近一级的不是默认值static的父元素(可以是absolute/relative/fixed等)来进行定位的,而不仅仅是相对于为position为relative的父级元素。父级元素还可以是absolute、fixed定位

absolute的定位基准不不仅仅是relative,还有absolute/fixed的,案例如下:

(下面content是absolute定位,在其外层套absolute/relative/fixed的定位方式,都可以作为absolute定位的基准)

效果如下:

position的值, relative和absolute分别是相对于谁进行定位,你真的知道吗?

代码如下:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			*{
				margin: 0;
				padding:0;
				box-sizing: border-box;
			}
			.box_relative{
				width:300px;
				height:300px;
				position: relative;
				top: 100px;
				left: 100px;
				border: 1px solid gray;
			}
			.box_absolute{
				width:300px;
				height:300px;
				position: absolute;
				top: 100px;
				left: 500px;
				border: 1px solid gray;
			}
			.box_fixed{
				width:300px;
				height:300px;
				position: absolute;
				top: 100px;
				right: 100px;
				border: 1px solid gray;
			}
			.content{
				width:100px;
				height:100px;
				position: absolute;
				top: 100px;
				left: 100px;
				border: 1px solid gray;
			}
		</style>
	</head>
	<body>
		<div class="box_relative">
			relative
			<div class="content">absolute</div>
		</div>
		<div class="box_absolute">
			absolute
			<div class="content">absolute</div>
		</div>
		<div class="box_fixed">
			fixed
			<div class="content">absolute</div>
		</div>
	</body>
</html>
           
  • sticky ,它会产生动态效果,很

    像relative和fixed的结合

    ,一些时候是relative定位,另一些时候自动变成fixed定位,因此,它能够形成"动态固定"的效果

    定位逻辑:

    当页面滚动,父元素开始脱离浏览器视口时(即部分不可见),只要与sticky元素的距离(与浏览器窗口的距离)达到生效门槛,relative定位自动切换为fixed定位;

    等到父元素完全脱离视口时(即完全不可见),fixed定位自动切换回relative定位。

    用途:

    网页的搜索工具栏,初始加载时在自己的默认位置(relative定位),页面向下滚动时,工具栏变成固定位置,始终停留在页面头部(fixed定位)。等到页面重新向上滚动回到原位,工具栏也会回到默认位置。

    position的值, relative和absolute分别是相对于谁进行定位,你真的知道吗?
    position的值, relative和absolute分别是相对于谁进行定位,你真的知道吗?
    示例代码:
<!DOCTYPE html>
<html>

	<head>
		<meta charset="UTF-8">
		<title></title>
		<style>
			body {
				height: 2000px;
				/* 为父容器设置一个很大的高度,方便演示 */
			}
			
			#father {
				width: 600px;
				height: 100%;
				background: lightpink;
				margin: 100px auto 1000px auto;
			}
			nav {
				position: sticky;
				top:50px;
				width: 500px;
				height: 50px;
				background: #096;
				margin: 10px auto;
			}
		</style>
	</head>

	<body>
		<main id="father">
			父元素
			<nav>导航栏</nav>
		</main>
	</body>

</html>
           

参考链接 :https://shixtao.cn/article/36

参考链接 :http://www.ruanyifeng.com/blog/2019/11/css-position.html

继续阅读