Most CSS properties are easy to understand. Often, applying any of them to a markup element gives immediate results - you just need to refresh the page, and you can see the effect of the application. However, there are some properties that are more complex and will only work under certain circumstances.
The z-index property belongs to the second group, which undoubtedly causes more confusion than any other. Ironically, however, with a full understanding of what z-index is, it is very easy to use and is often an effective way to overcome many layout problems.
In this article, we will look at what z-index is, what problems there are in understanding it, and also discuss some examples of its use. We will also consider the difference in how browsers handle it, especially in previous versions of Internet Explorer and FireFox.
So what is this property?
The z-index property determines the level of placement in the stack, the depth of the html element. "Depth level" means the position of the element along the Z axis (as perpendicular to the X and Y axes of the screen). The higher the z-index value, the taller the element will be.
Natural arrangement of elements
On a page, the normal placement of elements (by which I mean along the Z axis) is determined by several factors. Below is a list of these factors, starting with the lowest elements. This list assumes that no element is explicitly assigned a z-index property.
- The background and borders of the element defining the stack context.
- Elements with negative stack context, in display order.
- Unpositioned (position: static), as well as without the float property set (float: none) block elements (display: block), in display order.
- Unpositioned, float-property-set block elements, in display order.
- Inline elements, in display order.
- Elements with the position property set, in display order.
Correct application of the z-index property can change the natural position in the stack.
Of course, the order of elements in a stack is not obvious until you need to display the elements one above the other. Therefore, to see the normal order of elements, the example below uses negative margins.
These elements have different background and border colors, and the last two are offset due to the negative margin property being set. This way you can see the natural placement of elements, each next one is “above” the previous one. These elements do not have a z-index property set, and their stacking order is natural.
Where might the problems be?
Let's look at the most popular problem among novice developers. The thing is that the z-index property only works on elements that have their position property set to absolute , fixed or relative .
To demonstrate this, let's display the same three elements, but with the z-index property set to try to change the order along the Z axis.
Let's set the gray element's z-index to 9999, the blue element to 500, and the brown element to 1. It's logical to expect the order to change. But not in this case, since the position property is static by default.
Let's set the position property to relative and see what happens:
But now we have the expected result. The order of the elements has changed, the gray element is on top of all, and the brown one is at the very bottom.
Syntax
The z-index property affects both block elements and inline elements. The value can be a positive or negative number, or the default is auto . The default value means that the element is at the same level as its parent.
Below is the CSS for the third example, where the z-index property is applied correctly:
#grey_box ( width: 200px; height: 200px; border: solid 1px #ccc; background: #ddd; position: relative; z-index: 9999; ) #blue_box ( width: 200px; height: 200px; border: solid 1px # 4a7497; background: #8daac3; position: relative; z-index: 500; ) #gold_box ( width: 200px; height: 200px; border: solid 1px #8b6125; background: #ba945d; position: relative; z-index: 1 ; )
Once again, especially for those new to CSS, the z-index property will not work unless you set the position property.
Use in javascript
You can affect the z-index property dynamically using javaScript. The syntax is similar to that of most CSS properties, using camel notation to replace the hyphen in CSS properties.
Var myElement = document.getElementById("gold_box"); myElement.style.position = "relative"; myElement.style.zIndex = "9999";
Incorrect implementation in IE and FireFox
In some cases, in IE6, IE7 and FireFox 2, there is an incorrect implementation of the z-index property.
Select element in IE6
In Internet Explorer 6, the select element is a windows control, for this reason it is always displayed on top of all elements, ignoring the normal placement order, as well as the position and z-index properties. The problem is shown in the picture below:
The select element is the first element in the document, its z-index property is set to 1, and its position is set to relative . The div is displayed after the select and its z-index is "9999". Based on all this, the div should be located above the select , as it happens in other browsers:
Choose Year - 2009 2010 2011
If you're not viewing this article in IE6, you'll see that the div is positioned above the select .
This IE6 bug is a big problem for dropdown menus when they need to overlap the select element. A solution might be to use JavaScript to temporarily hide the selectors, and then show them again after the menu disappears. Another solution could be to use an iframe.
Positioned parents in IE6/IE7
Internet Explorer versions 6 and 7 do not correctly reset the stack context with respect to the closest positioned parent. To demonstrate this error, we will again display two divs. But this time we'll wrap the first one in a positioned element.
The gray element has a z-index of 9999, the blue element has a z-index of 1, both elements are positioned. Therefore, if implemented correctly, the gray element will appear on top of the blue one.
If you open this page in IE6 or IE7, you will see that the blue element overlaps the gray one. This happens because the gray element is wrapped in another div whose position is set to relative .
Both browsers "reset" stack context on relatively positioned elements, even though they shouldn't. The gray element has a higher z-index than the blue element, so it should appear higher. There is no such problem with other browsers.
Negative values in FireFox 2
In FireFox 2, elements with a negative z-index are below the stacking context, instead of being above the background and borders of the element that forms the stacking context. You can see an example in the picture:
Below is the html version
As you can see, the background of the gray element (which forms the stack context) is below the blue one, and the text (which is the inline element in the gray element) is above it, following the natural layout rules described above.
Examples of using
The original article gives many examples of using the property. Honestly, I'm too lazy to translate this, basically it's a screenshot, a small comment and a link. If you really need it, then write, I’ll make time for it.
Any positioned elements on a web page can be stacked on top of each other in a specific order, thereby simulating a third dimension perpendicular to the screen. Each element can be either below or above other objects on the web page, their placement along the z-axis is controlled by z-index . This property only works for elements whose position value is absolute , fixed , or relative .
brief information
Designations
Description | Example | |
---|---|---|
<тип> | Indicates the type of the value. | <размер> |
A && B | The values must be output in the order specified. | <размер> && <цвет> |
A | B | Indicates that you need to select only one value from the proposed ones (A or B). | normal | small-caps |
A || B | Each value can be used independently or together with others in any order. | width || count |
Groups values. | [ crop || cross ] | |
* | Repeat zero or more times. | [,<время>]* |
+ | Repeat one or more times. | <число>+ |
? | The specified type, word, or group is optional. | inset? |
(A, B) | Repeat at least A, but no more than B times. | <радиус>{1,4} |
# | Repeat one or more times separated by commas. | <время># |
Values
Integers (positive, negative and zero) are used as values. The higher the value, the higher the element is compared to those elements that have a lower value. If the z-index value is equal, the element in the foreground is the one described below in the HTML code. It is acceptable to use a negative value.
In addition to numeric values, auto is used - the order of elements in this case is built automatically, based on their position in the HTML code and their belonging to the parent, since child elements have the same number as their parent element.
Example
In this example, when you hover over the map, it comes to the front edge, partially overlapping the rest of the images (Fig. 1).
Rice. 1. Changing the order of cards
Object Model
An object.style.zIndex
Note
List created with
Internet Explorer versions up to and including 7.0 interpret auto as 0.
In Firefox browser versions up to and including 2.0, a negative z-index value positions the element below the background of the web page and its content.
Specification
Each specification goes through several stages of approval.
- Recommendation - The specification has been approved by the W3C and is recommended as a standard.
- Candidate Recommendation ( Possible recommendation) - the group responsible for the standard is satisfied that it meets its goals, but requires help from the development community to implement the standard.
- Proposed Recommendation Suggested Recommendation) - at this stage the document is submitted to the W3C Advisory Council for final approval.
- Working Draft - A more mature version of a draft that has been discussed and amended for community review.
- Editor's draft ( Editorial draft) - a draft version of the standard after changes were made by the project editors.
- Draft ( Draft specification) - the first draft version of the standard.
The z-index property controls order of application positioned elements when they overlap each other. The property accepts positive and negative integer values.
In a normal flow, position: static elements are placed sequentially one after the other in the order in which they are defined in the html document. The default is z-index: auto; .
Rice. 1. Positioning elements along the Z axis
The z-index property specifies the order of elements along the Z axis. Normally, elements with a high index value will overlap elements with a lower value and auto value, placing them in the foreground.
Rice. 2. Impact of the z-index property on positioned elements
Overlay context
If the elements' z-index and position properties are not explicitly set, the overlay context is the order in which they appear in the source code. If elements do not have a z-index specified, the browser renders elements on the page in the following order:
Root element
Positioned elements in the order they appear in the source code. The last one will be located in the foreground.
Rice. 3. Default order of elements in 3D space
Lorem ipsum dolor sit amet, consectetur adipiscing elit...
As can be seen from the figure, an element with position: absolute; is in the foreground, followed by the text, below it are floating elements with float: left; , non-positioned block elements are placed in the background (since floating and positioned elements are removed from the flow, block-level non-positioned elements ignore them and are placed one after another, in accordance with the markup, so the element .
The z-index property creates a new overlay context. It allows you to change the stacking order positioned elements. Elements will be displayed on the page in the following order (if they are not set to properties that affect the overlay context - opacity , filter , transform):
Root element , which contains all the elements of a web page.
Positioned elements with a negative z-index value.
Block elements, not floating or positioned.
Floating floats are not positioned elements in the order they appear in the source code.
Inline non-positioned elements (text, images).
Positioned elements with z-index values: 0; and z-index: auto; .
Positioned elements with positive z-index values. A high index value will render the element in the foreground. Elements with equal z-index values will be rendered according to their location in the source code.
Rice. 4. The z-index property creates a new context for overlaying elements in 3D space
From the author: Welcome to our A to Z CSS tutorial series! In this series I will tell you about CSS values and properties starting with different letters of the alphabet. Sometimes a tutorial isn't enough, and in this article I'll give you a couple of quick tips on working with the z-index property.
The full video tutorial and its text version on the z-index property can be viewed at the link.
Z stands for z-index
As you might expect, the last article in the series will be entirely devoted to the z-index property.
As mentioned in the video tutorial, the z-index property controls the order of layers in a document. There are several complex issues associated with the stack context, which were discussed in the video tutorial, but in general, the z-index property has rather limited functionality.
z-index only works on positioned elements
If you need to change the order of layers on elements, you can do this using the z-index property. However, this property will only work with elements that have their position property set to absolute, relative, or fixed.
Precise positioning of elements is essential when creating complex layouts and interesting interface patterns, but we all want to be able to change the order of layers without having to move an element from its original position on the page.
If you just need to change the order of the layers, you can simply set the position property to relative and leave out the top, right, bottom, or left. The element will remain in its place, the structure of the document will not be disrupted, and the z-index property will work as it should.
You can specify negative values in the z-index property
Layers are often used to create complex geometric shapes or UI components. This layering involves placing elements one above the other with a constantly increasing z-index value. To move an element down a level, simply specify a lower z-index value, but this property also accepts negative values.
Negative values can be used with pseudo-elements to place them behind the parent element's content.
To place the :before or after pseudo-elements below the parent element's text, you must specify a negative value. This is how the stack works.
Take a look at the CodePen demo below, you can play around with different z-index values.
Use 100 as increment for z-index
When working with z-index, it is not customary to write code like this:
Modal (z-index: 99999; )
Modal ( z-index: 99999; |
It pains me to look at this code. Things get even worse when you add!important. Code like this is a sign that the developer does not understand the context of the stack and is trying to force one layer on top of another.
Instead of using arbitrary numbers like 9999, 53, or 12, we can systematize our z-index scale and put it in order. And it's not because I'm a developer with obsessive-compulsive disorder. Honestly.
As an increment for z-index, I do not use a single digit number, but 100.
Layer-one (z-index: 100;).layer-two (z-index: 200;).layer-three (z-index: 300;)
This manual approach to creating a z-index system is very robust, but it can become even more flexible when paired with a preprocessor like Sass. That's all, friends. This was the last article in the CSS A to Z series! We hope you enjoyed it and learned a lot about CSS properties. |
Hello, dear readers of the blog site! From time to time I allow myself to add materials to the collection and today we will talk about the z-index property, which affects the positioning of elements on a web page.
You need to understand that this rule only works for positioned tags for which the property is specified. That is, for the standard document flow (where positioning is not specified or its parameter is defined as static), it will not work. Below I will demonstrate how z-index works using a specific example.
How z-index determines element positions
So, for each element in CSS there is its own place on the web page in accordance with the styles prescribed for it. The location of all blocks relative to each other is determined using a coordinate system.
In general, the reference point is in the upper left corner of the viewing area (browser window). In this case, the X and Y axes determine the location of elements in the plane of the monitor screen. But the Z axis, as you probably guessed, allows you to model a spatial coordinate system.
It is located perpendicular to the plane formed by X and Y, and is directed directly at us. It goes without saying that the Z axis reference point is zero. The zero point contains all static elements for which the position static property is defined (normal positioning).
By default, if position is not specified at all, then this situation is absolutely equivalent to that as if the static parameter was specified. In this case, all HTML elements of the page are rendered on the standard stream. Thus, position, like, for example, float (see information about creating floating elements in CSS) makes it possible to change the usual ordering option to solve special layout problems.
Even though static web elements have a z value of zero, meaning they are positioned in the X-Y plane, there are rules for them if they start to collide with each other.
The basic rule is: a web element defined by a tag that is located lower in the HTML code of the page will be located closer to us. That is, it will overlap on top the block whose code is located above.
But clearly positioned (dynamic) elements (with relative, absolute, fixed values) are located above all static ones. In the relationship between dynamic web elements, the same law will apply: the one located lower in the code is closer to us (above the others).
This is where the final word can be said z-index property. The higher its value in numerical terms, the higher the corresponding element of the web page will be located. But all this works, as I said, only for elements with absolute, relative or fixed positioning. The syntax for z-index parameters is as follows:
Z-index: number|auto|inherit
Numeric values can be anything: both negative and positive, including zero. The auto parameter predetermines the automatic arrangement of web elements in accordance with their order in the HTML code, taking into account their parentage. The inherit value indicates what the parent's z-index is.
Now the time has come to direct our research in a practical direction in order to confirm the theoretical calculations. I'll take three relatively positioned ones (with the position: relative property specified) as an example. For clarity, I will write down the color shade, frame for each, and also indicate the left and top margins, width and height:
On the web page, after the browser interprets the HTML code, these three blocks will look like this:
Please note that the containers are located in full accordance with the rule stated above: the lower blue overlaps the red one located slightly higher and that, in turn, which is even higher green. Now let’s add a z-index property with a value of 1 to the red block:
The picture will change:
As you can see, the red container gets an advantage and is now located above the others. Next, let's try to add z-index to the green block, but with a value of 2:
The result will be like this:
It is clear that the green container that has received the highest z-index value is now higher than the others. Thus, all the arguments given at the beginning are fully confirmed by practical experiments. The main thing to remember is that the z-index property only works with explicitly positioned web elements.