position :static

静态定位/常规定位/自然定位

作用:使元素定位于常规流/自然流中

特点:

  1. 忽视top、bottom、left、right、z-index,是这些关键字作用失效

  2. 如果两个元素都设置了外边距,最终的外边距取决于外边距大的

  3. 在具有固定width和height值时的元素,如果把左右边距设置成auto,则左右边距会自动扩大占满剩余宽度,实现这个块水平居中的效果

案例1(解释第一个特点):

在这个案例中,有三个盒子,先是按照自然流顺序。

<body>
	<div class="box">box</div>
	<div class="box">box</div>
	<div class="box">box</div>
</body>

并且给每个盒子加了一个box类。又加了一个相对定位,top为10px。

*{
	margin: 0;
	padding: 0;
}
.box{
	height: 200px;
	width: 200px;
	border: 2px solid;
	text-align: center;
	line-height: 200px;
	position: relative;
	top: 10px;
}

效果:

这里先不说加完position:relation;top:10px;是什么意思,其效果就是让每个盒子都下移10px; 

然后给第二个盒子加这样一些属性:

.box:nth-child(2){
	position: static;
	border-color: red;
}

然后盒子就变成这样了 

 

为什么会这样呢?

这是因为加了position:static之后第二个盒子的top:10px;就失效了,第二个盒子就回到了原来的位置。这就是static的第一个特点。

案例二(解释第二个特点)

第二个特点其实在没加position:static的时候也是这样的

代码如下:把position:static去掉的话效果是一样的。

<!DOCTYPE html>
<html>
	<head>
		<meta charset="{CHARSET}">
		<title></title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			.box{
				height: 200px;
				width: 200px;
				border: 2px solid;
				text-align: center;
				line-height: 200px;
				position: static;
			}
			.box:nth-child(1){
				margin-bottom: 10px;
			}
			.box:nth-child(2){
				margin-top: 30px;
			}
		</style>		
	</head>
	<body>
		<div class="box">box</div>
		<div class="box">box</div>
	</body>
</html>

案例三(第三个特点)

这个案例和第二个一样,在不加position定位的时候也有这样的效果。但是这个加不加定位只能在水平居中,垂直无法居中。

效果:

 代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="{CHARSET}">
		<title></title>
		<style type="text/css">
			*{
				margin: 0;
				padding: 0;
			}
			.parent{
				width: 500px;
				height: 500px;
				margin: 0 auto;
				border: 1px red solid;
			}
			.child{
				width: 200px;
				height: 200px;
				background: sandybrown;
				margin-left: auto;
				margin-right: auto;
				position: static;
			}
		</style>		
	</head>
	<body>
		<div class="parent"><div class="child"></div></div>
	</body>
</html>

 如果想看其他定位方式(relative |absolute |fixed |sticky )的话,可以去我的博客里面搜索,都有详细的总结。

更多推荐

position之static