- z-index
- Интерактивный пример
- Синтаксис
- Значения
- Формальное определение
- Формальный синтаксис
- Примеры
- Визуальное наложение элементов
- HTML
- CSS
- Результат
- Спецификации
- Поддержка браузерами
- Смотрите также
- Found a content problem with this page?
- MDN
- Support
- Our communities
- Developers
- CSS z-index Property
- Browser Support
- CSS Syntax
- Property Values
- CSS z-index
- How does the Z-index property work in CSS?
- Examples of CSS z-index
- Example #1
- Example #2
- Example #3
- Conclusion
- Recommended Articles
- How can I use an element as a background image with z-index?
- HTML
- CSS
- 6 Answers 6
z-index
CSS-свойство z-index определяет положение позиционированного элемента и его дочерних элементов или флекс-элементов по оси z. Перекрывающие элементы с большим значением z-index будут накладываться поверх элементов с меньшим z-index.
Интерактивный пример
Для позиционированного элемента (т.е. если у него задано свойство position со значением, отличающимся от static ) свойство z-index отвечает за:
Синтаксис
/* Ключевое слово */ z-index: auto; /* Значения типа */ z-index: 0; z-index: 3; z-index: 289; z-index: -1; /* Отрицательные значения понижают приоритет */ /* Глобальные значения */ z-index: inherit; z-index: initial; z-index: revert; z-index: revert-layer; z-index: unset;
Значением свойства z-index может быть либо auto , либо целое число ( ).
Значения
Элемент не будет создавать нового локального контекста наложения. Порядок наложения блока в текущим контексте наложения будет равен 0 .
Формальное определение
Формальный синтаксис
Примеры
Визуальное наложение элементов
HTML
div class="wrapper"> div class="dashed-box">Пунктирный блокdiv> div class="gold-box">Блок золотого цветаdiv> div class="green-box">Зелёный блокdiv> div>
CSS
.wrapper position: relative; > .dashed-box position: relative; z-index: 1; border: dashed; height: 8em; margin-bottom: 1em; margin-top: 2em; > .gold-box position: absolute; z-index: 3; /* помещаем .gold-box поверх .green-box и .dashed-box */ background: gold; width: 80%; left: 60px; top: 3em; > .green-box position: absolute; z-index: 2; /* помещаем .green-box поверх .dashed-box */ background: lightgreen; width: 20%; left: 65%; top: -25px; height: 7em; opacity: 0.9; >
Результат
Спецификации
Поддержка браузерами
BCD tables only load in the browser
Смотрите также
Found a content problem with this page?
This page was last modified on 7 нояб. 2022 г. by MDN contributors.
Your blueprint for a better internet.
MDN
Support
Our communities
Developers
Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.
CSS z-index Property
The z-index property specifies the stack order of an element.
An element with greater stack order is always in front of an element with a lower stack order.
Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
Note: If two positioned elements overlap without a z-index specified, the element positioned last in the HTML code will be shown on top.
Default value: | auto |
---|---|
Inherited: | no |
Animatable: | yes. Read about animatable Try it |
Version: | CSS2 |
JavaScript syntax: | object.style.zIndex=»-1″ Try it |
Browser Support
The numbers in the table specify the first browser version that fully supports the property.
CSS Syntax
Property Values
Value | Description | Demo |
---|---|---|
auto | Sets the stack order equal to its parents. This is default | Demo ❯ |
number | Sets the stack order of the element. Negative numbers are allowed | Demo ❯ |
initial | Sets this property to its default value. Read about initial | |
inherit | Inherits this property from its parent element. Read about inherit |
CSS z-index
The z-index property in CSS decides the stack order of the element like an image or box or any character content or button etc. An element with the highest or greater stack order value will always be in front of the element with the lower stack order value. Remember that the z-index only worked with position elements like absolute, position: relative, and position: sticky. This clears a point that the z- index property can be applied with positioned elements in the z-order. Element with a higher z index value always overlapped by the z index with a smaller value.
Web development, programming languages, Software testing & others
Real-Time Example: We have a requirement to overlap images with content. In general, CSS properties can’t provide this feature, which will give the image on top of the text, but we don’t want this. So by using the z-index property, we can make content on top of the image.
Why do we use CSS in HTML?
- Provide common Logic between all the pages. Instead of writing the same style logic in each HTML page, we use CSS files for writing common logic.
- And it includes a CSS page in each HTML page with a tag.
How does the Z-index property work in CSS?
Z- index property only works with position elements like:
Z-index image with values:
Examples of CSS z-index
Given below are the examples:
Example #1
Z Index with Image
The z-index property in CSS decides the stack order of the element like image or box or any character content or button etc. An element with highest or greater stack order value will be always in front of the element with lower stack order value. Keep in mind that z-index only worked with position elements like position: absolute, position: relative, position: sticky. This clear a point that z- index property can be applied with positioned elements in z order. Element with a higher z index value always overlapped by the z index with smaller value.
Real Time Example: We have requirement that we want overlap image with a content. In general CSS properties can't provide this feature, this all will give the image on top of the text but we don't want this. So by using z-index property we can make content on top of the image.
CSS Code: ZIndexFile.css
Explanation:
As we see above, we got a text on top of the image, but the text overlaps if we remove the z index property.
Example #2
Z Index with Content
The z-index property in CSS decides the stack order of the element like image or box or any character content or button etc. An element with highest or greater stack order value will be always in front of the element with lower stack order value. Keep in mind that z-index only worked with position elements like position: absolute, position: relative, position: sticky. This clear a point that z- index property can be applied with positioned elements in z order. Element with a higher z index value always overlapped by the z index with smaller value. Real Time Example: We have requirement that we want overlap image with a content. In general CSS properties can't provide this feature, this all will give the image on top of the text but we don't want this. So by using z-index property we can make content on top of the image. Paramesh Box
CSS Code: ZIndexFile.css
h1 < color: blue; text-align: center; >.topDiv < position: relative; height: 8em; color: navy; margin-bottom : 1em; margin-top : 2em; z-index: 1; border: solid; margin-bottom: 1em; margin-top: 2em; font-size: 28px; >.spanContent < position: absolute; width: 80%; background : fuchsia; left: 60px; top: 3em; z-index: 3; font-size: 28px; > .boxSpan < position: absolute; z-index: 2; width: 20%; top: -25px; height: 7em; opacity: 0.9; left: 65%; background : lightgreen; font-size: 28px; >
Explanation:
As you can see above, whichever z index value is more significant always overlaps the lower index value content.
Example #3
Z Index with Box Shapes
CSS Code: ZIndexFile.css
h1 < color: green; text-align: center; >.box1 < position: relative; top: 10px; left: 80px; z-index: 2 background-color: red; width: 400px; height: 200px; >.box2 < position: relative; top: -60px; left: 35px; z-index: 1; background-color: yellow; width: 400px; height: 200px; >.box3 < position: relative; top: -220px; left: 120px; z-index: 3; background-color: green; width: 400px; height: 200px; >.box4 < position: relative; top: -320px; left: 220px; z-index: 4; background-color: orange; width: 400px; height: 200px; >.box5
Explanation:
As you can see above, whichever z index value is greater always overlaps the lower index value box.
Conclusion
Z index in CSS property is used to put any element on top of the other element. But the Z index can be applied with only positioned elements like absolute, relative, sticky, etc.
Recommended Articles
We hope that this EDUCBA information on “CSS z-index” was beneficial to you. You can view EDUCBA’s recommended articles for more information.
38+ Hours of HD Videos
9 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
149+ Hours of HD Videos
28 Courses
5 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
253+ Hours of HD Videos
51 Courses
6 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
CSS Course Bundle — 19 Courses in 1 | 3 Mock Tests
82+ Hours of HD Videos
19 Courses
3 Mock Tests & Quizzes
Verifiable Certificate of Completion
Lifetime Access
4.5
How can I use an element as a background image with z-index?
I am using an image (in an tag) as a background. I want it to always be the furthest back object. But my paragraph isn’t showing up because it is covered up by the image. I know it has something to do with the z-index, but I can’t get it working.
HTML
This is the first paragraph in the body of your new HTML file!
asdfas
CSS
I guess background-size isn’t in old IEs. Still — why do you want to stretch it? That usually looks awful.
6 Answers 6
It seems like the image should be fixed, not the body.
position: absolute would also work, depends on the desired effect, in this case the OP wants a fixed background.
The paragraph or content in front if it needs to have position: relative , otherwise anything with a z-index takes precedence.
I want to just fix it for the background image so I don’t have to keep applying position relative to all future elements
@stackover: you can’t, without setting other things to be further forward than the background image. As I suggest in my answer, your best bet (aside from just not worrying about background-size in IE 8) is to wrap all your other page content in an element with a z-index higher than your background tag.
If you insist on using an img or another element in place of a background-image on the body, then you should also wrap your content in a div or another container so you only need to set position: relative on that container and all of the children show up correctly. Obviously a background-image on the body would be the best option here.
You can do this in pure CSS, yes even for ancient browsers. This should cover IE5.5+:
Aspect ratio not preserved using the filter . very true, it does not scale preserving ratio the same way that background-size:cover; does. This is a very good article, though, about different methods to use:
They provide multiple CSS-only, as well as jQuery, methods. One is bound to provide what you want.
very true. updated my answer with a link to an article that describes multiple methods, hopefully one will be the answer he wants. 🙂
I can’t recommend highly enough using backstretch.js. I’ve used it for a lot of projects as there is no real solution to preserving aspect ratio of an image in CSS. If you’re only supporting IE9+ then by all means, PlantTheIdea’s answer is the best. But for anyone that is coming here and needs to preserve aspect ration for IE8- and if they need to use an instead of background-image then use this great little plugin.
You can use it as a total background with just one line:
Or you can set it as the background on any element:
$("#demo").backstretch("http://dl.dropbox.com/u/515046/www/garfield-interior.jpg");
You can also pass multiple images into the function and other parameters to create slideshows etc.