CSS Positioning

发布时间: 2016-12-02 10:57:57 作者: 大象笔记

absolute

绝对是指,相对网页的坐标系来说的。这是我最初的理解,后来在实战中 z-index 从精通到入门 ,发现我的理解有误。

看一下 MDN 的说明

Elements that are positioned relatively are still considered to be in the normal flow of elements in the document. In contrast, an element that is positioned absolutely is taken out of the flow and thus takes up no space when placing other elements. The absolutely positioned element is positioned relative to nearest positioned ancestor (non-static). If a positioned ancestor doesn't exist, the initial container is used.

几个要点

float 不能与 absolute/fixed position 同时作用于一个元素。因为这不合逻辑。。。

relative

这里的相对,是指相对自己原来的位置。例如,span b 原来在 span a 的右侧,紧贴着。使用 relative 之后,left 10px 会使其右移 10px.

fixed

这里的 fixed, 是只相对于显示屏是 fixed 的。但是相对网页的顶部来说不是。

应用场景:适用于 fixed sidebar 的实现。

static

浏览器的默认值,即默认的自上至下的布局方式。通常不需要指定。

需要吐槽的是,这几个值的命名都非常之不好记。

absolute 与 fixed 的区别

absolute 是以 nearest positioned ancestor (non-static) 为坐标系(默认网页顶部),fixed 是以显示器屏幕为坐标系。

为何 absolute positioning 的 box 通常使用 relative box 作为 container

想想 absolute 的定义

absolute 是以 nearest positioned ancestor (non-static) 为坐标系

那么使用排除法,除了 static 只剩下 fixed, absolute, relative

这就是为何总是看到 absolute 的父级 box 为 relative 的原因。

<div>
	<div class="card">
		CODE
	</div>
	<div class="card">
		CODE
	</div>
	<div class="card">
		CODE
	</div>
	<div class="card" style="position: absolute; left: 50px; top: 50px; background-color: red;">
		CODE

		<div class="card" style="position: absolute; left: 50px; top: 50px;">
			CODE5
		</div>
	</div>
</div>

.card {
	width: 200px;
	height: 200px;
	background-color: yellow;
	margin: 10px;
}
我是一名山东烟台的开发者,联系作者