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
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.

The Role of HTML: Structuring Web ContentThe Role of HTML: Structuring Web ContentApr 11, 2025 am 12:12 AM

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTML and Code: A Closer Look at the TerminologyHTML and Code: A Closer Look at the TerminologyApr 10, 2025 am 09:28 AM

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS, and JavaScript: Essential Tools for Web DevelopersHTML, CSS, and JavaScript: Essential Tools for Web DevelopersApr 09, 2025 am 12:12 AM

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

The Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesThe Roles of HTML, CSS, and JavaScript: Core ResponsibilitiesApr 08, 2025 pm 07:05 PM

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

Is HTML easy to learn for beginners?Is HTML easy to learn for beginners?Apr 07, 2025 am 12:11 AM

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

What is an example of a starting tag in HTML?What is an example of a starting tag in HTML?Apr 06, 2025 am 12:04 AM

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.

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 Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

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.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools