position四个属性简要分析

202 阅读1分钟

@TOC

今天在笔试的时候遇到position属性问题,脑海里有2/3的印象,但是答完后不确定,于是赶紧又百度并实操总结了一下。position有4个属性,分别是static,fixed,relative和absolute,它们各自的作用和区别如下:


一、static

static是默认定位,即没有定位,元素出现在正常的流中。这种定位不会受到top、bottom、left、right的影响。 代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box{
				height: 200px;
				width: 200px;
				background-color: pink;
				}
			.content{
				height: 80px;
				width: 80px;
				background-color: coral;
				position: static;
				top: 20px;
				left: 20px;
			}
		</style>
	</head>
	<body>
		<div class="box">
		    <div class="content"></div>
		</div>
	</body>
</html>

效果图: 在这里插入图片描述left,top,right,bottom均不对content盒子起作用

二、fixed

fixed定位:元素相对于浏览器窗口是固定的,即使窗口滚动它也不会滚动,且fixed定位使元素脱离文档流,因此不占据空间,所以会和其他元素发生重叠。 代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box{
				height: 1200px;
				background-color: pink;
				}
			.content{
				height: 200px;
				width: 200px;
				background-color: coral;
				position: fixed;
				bottom: 0px;
				right: 0px;
				}
		</style>
	</head>
	<body>
		<div class="box">
		    <div class="content"></div>
		</div>
	</body>
</html>

效果图: 在这里插入图片描述 无论如何滑动,content盒子始终保持在原来的位置

三、relative

相对定位,不脱离文档流,参考自身静态位置通过 top,bottom,left,right 定位 代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box{
				height: 200px;
				width: 200px;
				background-color: pink;
				}
			.content{
				height: 80px;
				width: 80px;
				background-color: coral;
				position: relative;
				left: 100px;
				top: 100px;
				}
		</style>
	</head>
	<body>
		<div class="box"></div>
		<div class="content"></div>
	</body>
</html>

效果图: 在这里插入图片描述 conten相对于自身移动,而不是相对于左上角最顶部

四、absolute

绝对定位的元素相对于最近的已定位父元素,如果元素没有已定位的父元素,那么它的位置相对于html。 代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box{
				height: 400px;
				width: 400px;
				background-color: pink;
				}
			.content{
				height: 200px;
				width: 200px;
				background-color: coral;
				position: relative;
				top:50px;
				}
			span{
				position: absolute;
				top: 100px;
				background-color: red;
				}
		</style>
	</head>
	<body>
		<div class="box">
		    <div class="content">
			<span>我在这里</span>
		    </div>
		</div>
	</body>
</html>

效果图: 在这里插入图片描述 content是span最近的父元素,span相对于content移动100px