拆解 CSS Stacking Contexts
In CSS, we can create “stacking contexts” where elements are visually placed one on top of the next in a three-dimensional sense that creates the perception of depth. Stacking contexts are incredibly useful, but they’re also widely misunderstood and often mistakenly created, leading to a slew of layout issues that can be tricky to solve.
在 CSS 中,我们可以创建“层叠上下文”,其中元素在视觉上一个叠加在另一个之上,形成一种三维深度感知。层叠上下文非常有用,但它们也被广泛误解,并且经常被错误地创建,导致一系列难以解决的布局问题。
Have you ever set z-index: 99999 on an element in your CSS, and it doesn’t come out on top of other elements? A value that large should easily place that element visually on top of anything else, assuming all the different elements are set at either a lower value or not set at all.
你是否曾在 CSS 中的一个元素上设置 z-index: 99999,但它并没有出现在其他元素上方?这样一个大的值应该很容易将该元素视觉上置于其他任何元素之上,前提是所有其他元素要么设置了较低的值,要么根本没有设置。
A webpage is usually represented in a two-dimensional space; however, by applying specific CSS properties, an imaginary z-axis plane is introduced to convey depth. This plane is perpendicular to the screen, and from it, the user perceives the order of elements, one on top of the other. The idea behind the imaginary z-axis, the user’s perception of stacked elements, is that the CSS properties that create it combine to form what we call a stacking context.
网页通常以二维空间表示;然而,通过应用特定的 CSS 属性,会引入一个想象的 z 轴平面来传达深度。这个平面垂直于屏幕,用户从中感知元素的顺序,一个叠在另一个上面。想象的 z 轴背后的想法,即用户对堆叠元素的感知,是创建它的 CSS 属性结合形成了我们称之为层叠上下文的东西。
We’re going to talk about how elements are “stacked” on a webpage, what controls the stacking order, and practical approaches to “unstack” elements when needed.
我们将讨论元素如何在网页上“stacked”,什么控制堆叠顺序,以及在需要时“unstack” 元素的实用方法。
About Stacking Contexts #
关于层叠上下文 #
Imagine your webpage as a desk. As you add HTML elements, you’re laying pieces of paper, one after the other, on the desk. The last piece of paper placed is equivalent to the most recently added HTML element, and it sits on top of all the other papers placed before it. This is the normal document flow, even for nested elements. The desk itself represents the root s...