search
HomeWeb Front-endHTML TutorialLet's talk about some interesting CSS topics (3) – How much do you know about stacking order and stack context?

Start this series and discuss some interesting CSS topics. Putting aside practicality, some topics are designed to broaden the ideas for solving problems. In addition, they involve some CSS details that are easily overlooked.

Compatibility is not taken into account when solving problems. The questions are wild and wild. Just say whatever comes to mind. If there are CSS properties that you feel are unfamiliar in the problem solving, go and study them quickly.

Keep updating, keep updating, keep updating, say important things three times.

All topics are summarized in my Github.

3. How much do you know about stacking level and stacking context?

z-index seems to be very simple. The priority of the cascading is determined based on the level of z-index. In fact, if you go deeper, you will find that there are things inside.

Look at the following question, define two div A and B, included under the same parent div tag. The HTML structure is as follows:

<div class="container">
    <div class="inline-block">#divA display:inline-block</div>
    <div class="float"> #divB float:left</div>
</div>

Their CSS definitions are as follows:

.container{
    position:relative;
    background:#ddd;
}
.container > div{
    width:200px;
    height:200px;
}
.float{
    float:left;
    background-color:deeppink;
}
.inline-block{
    display:inline-block;
    background-color:yellowgreen;
    margin-left:-100px;
}

To describe it roughly, it means that two DIVs with a common parent container overlap. Is display:inline-block stacked on top, or float:left stacked on top?

Pay attention to the order of DOM here. display:inline-block is generated first, and then float:left is generated. Of course, you can also reverse the order of the two DOMs as follows:

<div class="container">
    <div class="float"> #divB float:left</div>
    <div class="inline-block">#divA display:inline-block</div>
</div>

会发现,无论顺序如何,始终是 display:inline-block 的 div 叠在上方。

Demo戳我。

这里其实是涉及了所谓的层叠水平(stacking level),有一张图可以很好的诠释:

运用上图的逻辑,上面的题目就迎刃而解,inline-blcok 的 stacking level 比之 float 要高,所以无论 DOM 的先后顺序都堆叠在上面。

不过上面图示的说法有一些不准确,按照 W3官方 的说法,准确的 7 层为:

  1. the background and borders of the element forming the stacking context.

  2. the child stacking contexts with negative stack levels (most negative first).

  3. the in-flow, non-inline-level, non-positioned descendants.

  4. the non-positioned floats.

  5. the in-flow, inline-level, non-positioned descendants, including inline tables and inline blocks.

  6. the child stacking contexts with stack level 0 and the positioned descendants with stack level 0.

  7. the child stacking contexts with positive stack levels (least positive first).

稍微翻译一下:

  1. 形成堆叠上下文环境的元素的背景与边框

  2. 拥有负 z-index 的子堆叠上下文元素 (负的越高越堆叠层级越低)

  3. 正常流式布局,非 inline-block,无 position 定位(static除外)的子元素

  4. 无 position 定位(static除外)的 float 浮动元素

  5. 正常流式布局, inline-block元素,无 position 定位(static除外)的子元素(包括 display:table 和 display:inline )

  6. 拥有 z-index:0 的子堆叠上下文元素

  7. 拥有正 z-index: 的子堆叠上下文元素(正的越低越堆叠层级越低)

所以我们的两个 div 的比较是基于上面所列出来的 4 和 5 。5 的 stacking level 更高,所以叠得更高。

不过!不过!不过!重点来了,请注意,上面的比较是基于两个 div 都没有形成 堆叠上下文 这个为基础的。下面我们修改一下题目,给两个 div ,增加一个 opacity:

.container{
    position:relative;
    background:#ddd;
}
.container > div{
    width:200px;
    height:200px;
    opacity:0.9; // 注意这里,增加一个 opacity
}
.float{
    float:left;
    background-color:deeppink;
}
.inline-block{
    display:inline-block;
    background-color:yellowgreen;
    margin-left:-100px;
}

Demo poke me.

You will see that the div of inline-block is no longer necessarily stacked on top of the div of float, but it is related to the stacking order of the DOM in the HTML code. The divs added later will be stacked first. above the added div.

The key point here is that the added opacity:0.9 allows both divs to generate the concept of stacking context. At this time, to stack the two, you need z-index. The higher the z-index, the higher the stacking level.

Stacking context is a three-dimensional concept of HTML elements. These HTML elements extend on an imaginary z-axis relative to the user facing the window (computer screen) or web page. HTML elements occupy the stacking context in order of priority according to their own attributes. Space.

So, how to trigger an element to form a stacking context? The method is as follows, excerpted from MDN:

  • Root element (HTML),
  • z-index value is not "auto" Absolute/relative positioning,
  • A flex item with a z-index value other than "auto", that is: parent element display: flex|inline-flex,
  • Elements with an opacity attribute value less than 1 (refer to the specification for opacity),
  • Transform attribute value is not "none" elements,
  • mix-blend-mode attribute value is not "normal" elements,
  • Elements whose filter value is not "none",
  • Elements whose perspective value is not "none",
  • Elements whose isolation attribute is set to "isolate",
  • position: fixed
  • Specify any CSS properties in will-change, even if you don’t specify the values ​​of these properties directly
  • -element with webkit-overflow-scrolling attribute set to "touch"

So, the purpose of adding the opacity attribute to the two divs above is to form a stacking context. In other words, adding opacity and replacing the attributes listed above can achieve the same effect.

In a stacking context, its child elements are also stacked according to the rules explained above. It is particularly worth mentioning that the z-index value of its child elements is only meaningful in the context of the parent cascading. This means that the z-index of the parent element is lower than another sibling element of the parent element, and it is useless no matter how high the z-index of the child element is.

Understanding the above stacking-level and stacking-context is the key to understanding the stacking order of CSS.

All the topics are summarized in my Github and posted to the blog in the hope of getting more exchanges.

This is the end of this article. If you still have any questions or suggestions, you can communicate more. It is an original article. The writing style is limited and the knowledge is shallow. If there is anything wrong in the article, please let me know.

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Future of HTML, CSS, and JavaScript: Web Development TrendsThe Future of HTML, CSS, and JavaScript: Web Development TrendsApr 19, 2025 am 12:02 AM

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

HTML: The Structure, CSS: The Style, JavaScript: The BehaviorHTML: The Structure, CSS: The Style, JavaScript: The BehaviorApr 18, 2025 am 12:09 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The Future of HTML: Evolution and Trends in Web DesignThe Future of HTML: Evolution and Trends in Web DesignApr 17, 2025 am 12:12 AM

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

HTML vs. CSS vs. JavaScript: A Comparative OverviewHTML vs. CSS vs. JavaScript: A Comparative OverviewApr 16, 2025 am 12:04 AM

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTML: Is It a Programming Language or Something Else?HTML: Is It a Programming Language or Something Else?Apr 15, 2025 am 12:13 AM

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML: Building the Structure of Web PagesHTML: Building the Structure of Web PagesApr 14, 2025 am 12:14 AM

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

From Text to Websites: The Power of HTMLFrom Text to Websites: The Power of HTMLApr 13, 2025 am 12:07 AM

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

Understanding HTML, CSS, and JavaScript: A Beginner's GuideUnderstanding HTML, CSS, and JavaScript: A Beginner's GuideApr 12, 2025 am 12:02 AM

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment