search
HomeWeb Front-endCSS TutorialWhat is CSS stacking context? what's the effect?

This article brings you what is CSS stacking context? what's the effect? It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What is CSS stacking context?

We have a basic style div, the style is as follows:

div{
    width: 200px;
    height: 200px;
    border:10px solid red;
    padding:15px;
    margin:12px;
}

The effect is as follows:

What is CSS stacking context? whats the effect?

A question here is: What is the relationship between border and background?

There are two options here:

  1. Parallel

  2. border closer to the user

  3. background closer to users

Which one will you choose?

In fact, it is very simple to understand this. We only need to set the border to semi-transparent to know the answer

border:10px solid rgba(255, 0, 0, 0, .3);

What is CSS stacking context? whats the effect?

It can be seen from the running results that red shows green, so the border is closer to the user. At this time, you will know that the div is not flat, but also has a hierarchical relationship on the vertical screen. Then this hierarchical relationship is called stacking Stacking context.

Then we write 'Hello, world' inside the div, the effect is as follows:

What is CSS stacking context? whats the effect?

Another question arises here , which layer is this 'Hello, world' on? Is it on the border or between the border and the background?

Here we only need to move 'Hello' to the border to know the reason. So how to move the text there? Here we use text-indent, the style is as follows:

div{
  width: 200px;
  height: 200px;
  border:10px solid rgb(255, 0, 0);
  padding:15px;
  margin:12px;
  background-color: green;
  text-indent: -20px;
}

The effect is as follows:

What is CSS stacking context? whats the effect?

You can see from the running effect that the text is above the border, so the text area (inline element) is closer to the user

What if there is another div inside the div? The code structure is as follows:

 // html
  <div>
    你好,CSS世界
    <div></div>
  </div>
    // css
   .parent{
      width: 200px;
      height: 200px;
      border:10px solid rgb(255, 0, 0);
      padding:15px;
      margin:12px;
      background-color: green;
      text-indent: -20px;
    }
    .child{
      height: 20px;
      background:purple;
    }

The effect is as follows:

What is CSS stacking context? whats the effect?

##Another question arises, is the purple area higher than the text area or vice versa? Woolen cloth?

How to verify this problem? We just need to move the div inside it up.

Note that position cannot be used here because in order to change the hierarchical structure, we only need to use margin-top, such as:

margin-top:-20px;
The effect is as follows:

What is CSS stacking context? whats the effect?

#You will find that the text area is above. Here we draw a conclusion:

If there are block-level elements in the div, the block-level elements cannot cover the inline elements. In other words, the inline elements are closer to the user What if there is text in the div? At this time we need to write a few words, the effect is as follows:

What is CSS stacking context? whats the effect?

You will find that the text area of ​​the child element will cover the text area of ​​the parent element.

So there is another small conclusion here: what appears after the text area will overwrite what appears before it.

Floating elements

Come to a basic structure:

  // html
  <div>
      你好
    <div>

    </div>
  </div>
  // css
.parent{
  width: 200px;
  height: 200px;
  border:10px solid rgb(255, 0, 0);
  padding:15px;
  margin:12px;
  background-color: green;
  color: aliceblue;
}
.float{
  height: 40px;
  width: 40px;
  background:purple;
  float: left;
}
The effect is as follows:

What is CSS stacking context? whats the effect?## I won’t explain the above code. I’m sure you all know it? According to the above routine, the same question is still here: Are you better at the top or this float element?

To verify this problem, also use text-indent to move the text to the left. Here I directly apply the effect:

What is CSS stacking context? whats the effect?# #From the renderings, we can conclude that the text area is above the floating cloud element.

那浮动元素是在 文字区域与内部块级元素之间呢,还是内部块级与border元素之间呢?换句话说就是 浮动元素与块级元素哪个离用户更近?

我们直接在父级元素写一个 child:

    // hmtl
  <div>
      你好
    <div></div>
    <div></div>
  </div>

  // css
  
 .child{
  height: 20px;
  background: black;
}

效果如下:

What is CSS stacking context? whats the effect?

从上可以看出浮云元素盖住了 child元素,说明浮动元素的层级是比块级元素高的。即浮动元素是在文字区域与块级元素之间的。

那浮动元素里面的文字与外面的文字是怎么样的呢?这边我直接在浮动里面加了 float文字,效果如下:

What is CSS stacking context? whats the effect?

你会发现 浮动里面的文字是盖不住浮动外面文字的。

绝对定位元素

在上面的基础上我们增加一个 relative 元素,如下:

  // htmk
  <div>
      你好
    <div>floatt</div>
    <div></div>
    <div></div>
  </div>
  
 // css
.relative{
  width: 100px;
  height: 100px;
  background: pink;
  margin-top: -15px;
}

效果如下:

What is CSS stacking context? whats the effect?

这时我们给类relative 加上一个:

position:relative;

效果如下:

What is CSS stacking context? whats the effect?

你会发现 relative 元素盖住了浮动元素,这说明 给元素加一个 relative 定位会增加对应的一个层级。检查 relative 元素,会看到:

What is CSS stacking context? whats the effect?

加了 position:relative定位会多了一个 z-index:auto 的东西,实际上你定位,都是按z-index来计算的。

这里我们给没有定位的 child元素加上一个z-index:

  <div>
      你好
    <div>floatt</div>
    <div></div>
    <div></div>
  </div>

效果如下:

What is CSS stacking context? whats the effect?

你会发现 child 元素并没有盖住 relative 元素!

这边直接 给了结论了:z-index 只有在 position:relative|absolute
才有效果,如果都是relative,z-index一样,那么后面会盖前面,z-index值大的会盖住小的。

我们接着在原有上加一个relative2,样式如下:

.relative2{
  width: 100px; 
  height: 150px;
  background: gold;
  margin-top: -15px;
  position: relative;
}

效果如下:

What is CSS stacking context? whats the effect?

此时给 relative2 加上一个 z-index:-1,在看

What is CSS stacking context? whats the effect?

又得出一个结论:z-index为负值时,是位于 background下面的

这时,我们给.parent元素添加以下两个样式:

  position: relative;
  z-index: 0;

这时的效果如下:

What is CSS stacking context? whats the effect?

这时奇怪的事情就出现了,z-index: -1 的跑到上面来了。

MDN上有对什么堆叠给出了一些内容,如下 :

What is CSS stacking context? whats the effect?

其实我们给.parent元素设置z-index:0 ,根据MDN说的,我们其实已经 创造一个层叠上下文 。

那什么是堆叠上下文?下面是张鑫旭一段原文:

What is CSS stacking context? whats the effect?

其实这跟美国一个大法官说的一句话很像:我不知道什么色情,但当我看到它是我就知道什么是色情。

CSS堆叠上下文也是类似的道理,你很难说出什么是CSS堆叠上下文,但只要它满足MDN列出的几种情况,它就是CSS堆叠上下文。

CSS堆叠层叠顺序

CSS堆叠上下文是有一个垂直屏幕上有一个上关系的,它们的关系如下:

What is CSS stacking context? whats the effect?

所以这就解释为什么z-index为负值的时候,它会在 background上面,因为我们 z-index:0 时就创建一个CSS堆叠上下文。

CSS堆叠上下文作用

下面给一个基本的内容:

   // html
  <div>
    <div>a
      <div>a1</div>
    </div>
    <div>b
      <div>b1</div>
    </div>
  </div>
  // css
 .parent{
  width: 200px;
  height: 200px;
  border:10px solid rgb(255, 0, 0);
  padding:15px;
  margin:12px;
  background-color: green;
}
.relative{
  width:100px;
  height:100px;
  background: orange;
  position: relative;
  border:1px solid red;
}
.a1{
  position: relative;
  background:green;
}
.b1{
  position: relative;
  background:red;
}

效果如下:

What is CSS stacking context? whats the effect?

接着我们在b1在添加以下样式:

   margin-top: -90px;

What is CSS stacking context? whats the effect?

b1会盖住a1,这个我们应该知道是什么原因了吧?因为a1 b1都是块级元素,后面会盖住前面的,没毛病!

那么 a1 和  b1 的CSS堆叠上下文是谁?

我们可以MDN给出的第一句:

What is CSS stacking context? whats the effect?

根元素,所以a1 和 b1的CSS堆叠上下文就是Html

接着给a1以下样式:

   z-index: 2;

接着给b1以下样式:

z-index: 0;

效果如下:

What is CSS stacking context? whats the effect?

a1跑到b1上面了,这个很好理解,因为 a1 的z-index:2 比 b1的z-index:0 在,所以a1在上面。

现在有一个问题,a1是永远盖住b1吗?

这边你可能会说,a1 的z-index:2比 b1的 z-index:0 永远都大,当然会盖住b1呀!是这样吗?我们试着改变一下CSS堆叠上下文。

我们分别给a 和 b各做一个CSS堆叠上下文: 如下:

.a{
  position: relative;
  z-index: 1;
}
.b{
  position: relative;
  z-index: 1;
}

效果如下:

What is CSS stacking context? whats the effect?

先分析a 和 b它们是谁覆盖谁,因为 两个定位和z-index都一样所以 b 会覆盖 a。还有一个现象有没有发现, b1 盖住了 a1? 明明 a1 的 z-index 大于 b1,这是为什么?为什么小的会盖住大的?为什么?

因为 b 比 a 高一点,所以 b 里面的内容都会比 a 高一点。这就是 CSS堆叠上下文一个特性。

比如说阿里巴巴有一个奇怪的部门叫做政委,是由马云等一些创始人组成的。在这个部门里面,你是不是都比其它部门要高级点。

所以 b1 虽然在 b 里面等级为0,在 b 是高级的一个部门,就是可以压过你 a 这个部门里面的 2 级的人。

The above is the detailed content of What is CSS stacking context? what's the effect?. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:segmentfault思否. If there is any infringement, please contact admin@php.cn delete
The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.