search
HomeWeb Front-endHTML TutorialWhat you don't know about the usage of z-index

Before starting today’s content, let us take a look at the following piece of code:

<style type="text/css"><br />   #div1,#div2{<br />       width:200px;<br />       height:200px;<br />       background-color:red;<br />       position: relative;<br />       z-index:1;<br />   }<br />    #div2{<br />        background-color:green;<br />        z-index:0;<br />    }<br />    #div1_1,#div2_1{<br />        width:100px;<br />        height:100px;<br />        background-color:black;<br />    }<br />    #div1_1{<br />        position:relative;<br />        z-index:-100;<br />        left:80px;<br />        top:140px;<br />    }<br />   #div2_1{<br />       background-color:yellow;<br />       z-index:999;<br />       position: relative;<br />       left:160px;<br />       top:-50px;<br />   }<br /><br /></style>
<br><div id="div1">
<br>    我是div1<br>    <div id="div1_1">
<br>        我是div1_1<br>    </div>
<br>
</div><br><div id="div2">
<br>    我是div2<br>    <div id="div2_1">
<br>        我是div2_1<br>    </div>
<br>
</div><br>

'

???excuse me? Why is the z-index value of div2_1 even 999, but it is still lower than the element level of div1? The z-index value of div1_1 is -100, but it is still higher than div1? Don't be anxious, just listen to me slowly.

First of all, when we are unfamiliar with something, we must first understand three things: 1. What is this thing? 2. What’s the use? 3. How to use?

We will also follow these three steps to explain the z-index attribute. First of all, first and second, what is this thing? Z-index is actually a common attribute in CSS. It is mainly used to set the stacking order of elements. To put it bluntly, if your webpage has three divs that overlap and they need to be displayed from the bottom to the top in a certain order, what should you do? Yes, because in general web development we are two-dimensional, and CSS introduces this attribute to help us layout better.

Secondly, let’s start to see how to use this thing. Let me introduce some conceptual things to you:

1. The z-index attribute sets the stacking order of elements. Elements with a higher stacking order will always be in front of elements with a lower stacking order

2. For elements of the same level, by default or in the case of position: STATIC, the elements at the back of the document flow will overwrite the previous ones

3. For elements of the same level, if the position is not static and z-index exists, the element with a larger z-index will cover the element with a smaller z-index, and the larger the z-index, the higher the priority

4. Under ie6/7, the position is not static, and the z-index does not exist, so the z-index is 0. In other browsers, the z-index is auto;

5. Elements whose z-index is auto do not participate in the comparison of hierarchical relationships. From the upward traversal to this point, elements whose z-index is not auto participate in the comparison

Note: If you set position:static, it will be the same as if you don’t set position. It will have no effect on the stacking level (the following examples will not explain it anymore, and the subsequent positions will not be static by default)

Below I will illustrate with a few examples:

1. The stacking order of elements when z-index and position are not involved:

The stacking rule of the above two divs is that the stacking level at the back is higher than the front. That is to say, if you use negative margin to move div2 to div1, the overlapping part will be displayed as div2 instead of div1. Then some students will ask, what if I add a div3 after div2? At this time, no matter how many divs you have behind you, the level will be the same as div2 and will not be higher than div2

2. When position is involved but z-index is not involved

eg:

<style type="text/css"><br />    /*定位规则,如果加position堆叠顺序优先,所以A此时变在B上面*/<br />    #a,#b{<br />        width:100px;<br />        height:100px;<br />        background-color:red;<br />    }<br />    #b{<br />        background-color:green;<br />        margin-top:-20px;<br />        margin-left:20px;<br />    }<br />    #a{<br />        position:relative;<br />    }<br /><br /></style>
<br><div id="a">
<br>    我是A<br>
</div><br><div id="b">
<br>    我是B<br>
</div><br><br>然后你看到的是这样的情况:

这说明啥呢,虽然b元素在a的后面,但是a加了position之后,他的堆叠层级就变高了,跑到了b的上面<br>,所以我们利用这个规则在无z-index参与的情况下也可以实现三层堆叠,比如这样:
 <style type="text/css"><br />        /*定位规则,在没有z-index干扰的情况下也可以三个div也可以做出堆叠效果哦*/<br />        #a,#b{<br />            width:100px;<br />            height:100px;<br />            background-color:red;<br />        }<br />        #b{<br />            background-color:green;<br />            margin-top:-20px;<br />            margin-left:20px;<br />        }<br />        #a_1{<br />            width:50px;<br />            height:50px;<br />            background-color:blue;<br />            position:relative;<br />            left:80px;<br />            top:50px;<br />        }<br /><br />    </style><br><br><br><div id="a">
<br>    我是A<br>    <div id="a_1">
<br>        我是A的子DIV<br>    </div>
<br>
</div><br><div id="b">
<br>    我是B<br>
</div><br>

3.有z-index参与的情况:<br>1.简单的堆叠:<br>#div1{<br>position:relative;<br>z-index:1;<br>}
#div2{<br>position:relative;<br><br>}
#div1{<br>position:relative;<br>z-index:0;<br>}
<div id="div1"></div><br><div id="div2">/div><br><div id="div3"></div>
<br>此时的层级顺序是,div1在最顶层,div2和div3均在第二层也就是最后一层。需要大家注意的一点,在position有值时,设置z-index为0和不设z-index是一样的。<br><br>2.相对复杂的堆叠(z-index的从父原则):<br>   意思就是子元素首先要看看父元素有无z-index,就像最开始的例子,当两个父元素div1的z-index为1,div2的z-index为0时,div1的所有的子元素及自己的层级就会比div2及其子元素高,这也解释了为什么div2_1的z-index值设为999了都还是在div1的下面。讲到这,上述例子还有一个问题,div1_1我都设了z-index为-100了,为什么还是比div1高呢。有些同学会想,我就是想让背景黑色div1_1在父元素div1的下边怎么办呢,所以这里还有一个原则:当父元素有设置z-index时,那么他的子元素的层级一定会比他高,所以如果你想让一个子元素的层级在父元素之下,你一直设置子元素的z-index,都设置成了z-index 1000了都,没有效果,那么不妨看看父元素是否也被设置了z-index吧!
<p> Finally, let me emphasize: z-index is allowed to be negative. Secondly, the value of z-index should be an integer without px. Many novices are used to writing width and height, so they add px to the z-index value. .Secondly, when using z-index, it must be used in conjunction with position. Regardless of whether the value of the position is fixed, absolute or relative, it is the same at the level where the value is static and the level without position is set. </p>
<p> To summarize, the above example seems very messy, and I really don’t know how to use it in actual situations. From personal experience, first look at whether there is a position. If there is no position, look at the hierarchy in order. If there is position, then check to see if there is z-index. When setting the z-index value for the child element of the parent element, be sure to pay attention to whether the parent element has z-index set, because the parent element will affect the level of the child element. This point It's very important, and it's also the most common mistake we make. If it doesn’t work when you set the z-index value of an element to the maximum or minimum, you might as well see if you don’t have a thorough understanding of the z-index principle of following the parent! Finally, let’s talk about something unrelated to this article. There are many css styles. Properties are all inherited, such as color. We need to slowly understand it. It is recommended that you have time to read about CSS inheritance knowledge. </p>
<p> </p>
<p> </p>
<pre class="brush:php;toolbar:false"><br><br>
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: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

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

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.