CSS Positioning

更新日期: 2016-12-02 阅读次数: 8216 分类: CSS

absolute

  • left
  • right
  • top
  • bottom

绝对是指,相对网页的坐标系来说的。这是我最初的理解,后来在实战中 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.

几个要点

  • absolute positioning 是三大 positioning scheme 中的一种,其作用的 box 将不参与 normal flow 的布局,也不会挤占 normal flow 布局的空间
  • absolute 并不完全是相对网页最左上角的坐标系而言,而是相对于 nearest positioned ancestor (non-static)

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

relative

  • top
  • left

这里的相对,是指相对自己原来的位置。例如,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

  • fixed。这种用的太少见了,也就是做 back to top 按钮,固定的 sidebar
  • absolute。absolute 本来就少见,再用 absolute 做 container 太奇葩了
  • relative。相对前面两个,这个最容易控制。对比 static, 只要不设置 left,top 实际上跟 static 没有区别,这个可以最放心使用

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

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

<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;
}

关于作者 🌱

我是来自山东烟台的一名开发者,有敢兴趣的话题,或者软件开发需求,欢迎加微信 zhongwei 聊聊, 查看更多联系方式