Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

学习 z-index #78

Open
YIXUNFE opened this issue May 6, 2016 · 2 comments
Open

学习 z-index #78

YIXUNFE opened this issue May 6, 2016 · 2 comments

Comments

@YIXUNFE
Copy link
Owner

YIXUNFE commented May 6, 2016

学习 z-index

z-index 是作为一个平常的 CSS 属性,我们在实践中经常会用到。它表示了元素在 Z 轴上的层叠关系,数值越大,就越上层。那么你知道在未设置 z-index 的时候,元素的层叠关系是如何的吗?带着这个疑问,我们一起来探寻关于 z-index 你所不知道的知识。


## z-index 的最大值

早年前不少面试官都会问候选人:你知道 z-index 的最大值吗?

当我被问及这个问题时,第一个反应就是:懵逼了!因为我在实践中从来没考虑过 z-index 还有最大值的情况,总觉得是值越大,就越高层。

这个问题其实换种说法就是在问,你知道带符号的 Int 类型(z-index 可以设负数值)的最大值吗?因为 z-index 的实际取值只有 Int 整型数字和 autoauto 可以简单认为是 0)。我们可以查看规范中的定义:

Values have the following meanings:

This integer is the stack level of the generated box in the current stacking context. The box also establishes a new stacking context. auto The stack level of the generated box in the current stacking context is 0. The box does not establish a new stacking context unless it is the root element.

所以 z-index 的最大值其实就是带符号的 Int 类型在不同操作系统下的最大值。

//32位操作系统下的有符号整型最大值
Math.pow(2, 31) - 1 //2147483647

z-index 设置的值超过了最大值时,浏览器会将它当 0 处理。


## z-index 与层叠等级 Stack Level ### 层叠上下文 Stacking Context

先介绍一下层叠上下文,除了根元素会产生根层叠上下文,其他的层叠上下文由定位且 z-index 为整数(auto 不行)的元素产生。层叠上下文在其父层叠上下文中类似原子般互不干扰,自成体系。

以后当有人问你 position: absolute 是根据什么定位的,你就可以用 “层叠上下文”回答了。

### 区别

渲染树(the rendering tree)在将元素绘制到画布时会根据层叠上下文中的层叠等级确定元素的绘制顺序。可以猜想,在同一层叠上下文中,层叠等级越低的越先绘制。

提到层叠等级可能很容易会被认为就是 z-index。其实它们并没有关系。层叠等级可以粗略分为 7 个等级。每个元素都会拥有自己的层叠等级。而 z-index 只作用于定位元素(非 static 的定位)。

层叠等级的 7 个划分

我们来看下规范中是如何定义 7 个层叠等级的:

在同一个层叠上下文中,层叠等级由低到高排列为:

  1. 元素的背景和边框形成的层叠上下文;
  2. z-index 为负数的层叠上下文;
  3. 正常文档流中,非行内,未定位(non-positioned)的元素;
  4. 未定位的浮动元素;
  5. 正常文档流中,未定位的行内元素,包括设置了 inline-blockinline-table 的元素;
  6. z-index 为 0 的层叠上下文;
  7. z-index 为正数的层叠上下文。

试试 DEMO


参考网址:https://www.w3.org/TR/CSS2/visuren.html#layers


## Thanks
@zcyzcy88
Copy link

zcyzcy88 commented May 6, 2016

PS: 设置 CSS translate 会影响层叠上下文

@YIXUNFE
Copy link
Owner Author

YIXUNFE commented May 9, 2016

@zcyzcy88 感谢补充。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants