首发于Html+Css
css:position定位属性详解

css:position定位属性详解

今天来为大家说一下最常用到的 position 定位属性

说定位之前先来看看什么是文档流:

w3c里面的解释是:正常流中的框属于格式化上下文,它可以是块的或内联的,但不能同时出现。块级框参与块格式化上下文。内联级别的框参与内联格式上下文。

个人解释一下:

每个块自上而下分成一行一行,并在每行中按从左至右的顺序排放元素;
每个非浮动块级元素都独占一行, 浮动元素则按规定浮在行的一端,若当前行容不下,则另起新行再浮动;
内联元素也不会独占一行,几乎所有元素(包括块级,内联和列表元素)均可生成子行,用于摆放子元素;
有三种情况将使得元素脱离文档流而存在,分别是 float,absolute ,fixed

position属性在通常情况下有4个可选值,分别是:static、relative、absolute、fixed。还有第5个属性sticky,因部分浏览器可能还不支持,所以就先不介绍

一、static 默认值

该关键字指定元素使用正常的布局行为,遵循正常的文档流对象。此时 top、right、bottom、left 属性无效

<style>
	.box {
		width: 300px;
		height: 300px;
		background-color: #ccc;
	}

	.box_chl {
		width: 100px;
		height: 100px;
		background-color: red;

		position: static;
		/* 这个left没有起作用 */
		left: 10px;
	}
</style>

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

二、relative 相对定位

relative 相对定位元素的定位是相对其正常位置。就是相对于原来的位置进行定位

<style>
	.box {
		width: 300px;
		height: 300px;
		background-color: #ccc;
	}

	.box_chl1 {
		width: 100px;
		height: 100px;
		background-color: red;
	}
	.box_chl2 {
		width: 100px;
		height: 100px;
		background-color: blue;
		
		position: relative;
	}
	.box_chl3 {
		width: 100px;
		height: 100px;
		background-color: green;
	}
</style>

<body>
	<div class="box">
		<div class="box_chl1"></div>
		<div class="box_chl2"></div>
		<div class="box_chl3"></div>
	</div>
</body>

这里可以看到蓝色块只加 relative 相对定位,不加 top、right、bottom、left 等属性时,他处在正常文档流中

如果给他添加了 top、right、bottom、left 等属性时,蓝色块 就会相对于其原位置进行移动

.box_chl2 {
		width: 100px;
		height: 100px;
		background-color: blue;
		
		position: relative;
		left: 15px;
		top: 15px;
	}

三、absolute 绝对定位

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

absolute 定位使元素的位置与文档流无关,因此不占据空间。绝对定位后会脱离文档流

absolute 定位的元素和其他元素重叠。

<style>
	.box {
		width: 300px;
		height: 300px;
		background-color: #ccc;
	}

	.box_chl1 {
		width: 100px;
		height: 100px;
		background-color: red;
		margin-left: 50px;
	}
	
	.box_chl1_demo{
		width: 50px;
		height: 50px;
		background: #00FFFF;
		position: absolute;
		left: 30px;
	}
</style>

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

这里可以看到蓝色块绝对定位后他是相对于 body 向左移动30px 定位的,因为它的俩个父元素都没有定位

如果给它的父元素加上定位后,它是相对于红色块来移动定位的

.box_chl1 {
		width: 100px;
		height: 100px;
		background-color: red;
		margin-left: 50px;
		position: relative;
	}

四、fixed 固定定位

元素的位置相对于浏览器窗口是固定位置。即使窗口是滚动的它也不会移动。

Fixed定位使元素的位置与文档流无关,因此不占据空间。

Fixed定位的元素和其他元素重叠。

<style>
	.box {
		width: 100%;
		height: 4000px;
		background-color: #ccc;
		background: linear-gradient(to top,#ffff00,#5500ff);
	}

	.box_chl1 {
		width: 100px;
		height: 100px;
		background-color: red;
		position: fixed;
		right: 50px;
		top: 50px;
	}
</style>

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

这里可以看到红色块相对于浏览器窗口位置是固定的

编辑于 2020-08-31 11:49