Почему z index не работает
Перейти к содержимому

Почему z index не работает

  • автор:

z — index

Если сложить элементы друг на друга, то какой из них будет сверху?

Время чтения: меньше 5 мин

Открыть/закрыть навигацию по статье
Контрибьюторы:

Обновлено 28 августа 2023

Кратко

Скопировать ссылку «Кратко» Скопировано

Обычно элементы на странице располагаются только в двух измерениях — x (горизонталь) и y (вертикаль). Но в отдельных случаях, когда позиционирование элементов отличается от статичного, появляется третье измерение z, отвечающее за глубину.

Свойство z — index позволяет управлять порядком наложения элементов друг на друга.

Пример

Скопировать ссылку «Пример» Скопировано

Возьмём самую частую ситуацию, где пригождается z — index — наложение полупрозрачной вуали поверх блока с фоном и текстом.

У нас будет разметка для шапки сайта:

   

Шапка сайта с классным заголовком

header> h1>Шапка сайта с классным заголовкомh1> header>

Для header мы зададим фоновое изображение и псевдоэлемент : : after с полупрозрачной вуалью, чтобы затемнить фон и чтобы текст лучше читался.

 header  position: relative; background: url("landscape.jpg") no-repeat center / cover;> header::after  content: ""; position: absolute; inset: 0; /* Полупрозрачный фиолетовый */ background-color: rgb(125 20 204 / 0.5);> header  position: relative; background: url("landscape.jpg") no-repeat center / cover; > header::after  content: ""; position: absolute; inset: 0; /* Полупрозрачный фиолетовый */ background-color: rgb(125 20 204 / 0.5); >      

Если всё оставить как есть, то псевдоэлемент с вуалью будет перекрывать текст заголовка и затемнять его. По логике браузера абсолютный псевдоэлемент накладывается поверх блока вместе со всем его содержимым. Представьте себе стопку листов, один поверх другого.

Нам такой эффект не нужен. Текст должен быть поверх вуали. Чем выше значение z — index , тем выше элемент в стопке наложения.

Добавим пару свойств. Отрицательный z — index опустит вуаль ниже текста:

 header  z-index: 0;> header:after  z-index: -1;> header  z-index: 0; > header:after  z-index: -1; >      

Как пишется

Скопировать ссылку «Как пишется» Скопировано

Значением свойства z — index может быть отрицательное или положительное целое число. Значение по умолчанию — auto .

 .selector  z-index: auto; z-index: 0; z-index: -1; z-index: 1; z-index: 9999999; z-index: -999999;> .selector  z-index: auto; z-index: 0; z-index: -1; z-index: 1; z-index: 9999999; z-index: -999999; >      

Как понять

Скопировать ссылку «Как понять» Скопировано

Браузер выстраивает блоки страницы не только по вертикали и горизонтали, но и по глубине. Это встроенный механизм обработки документа. Чем ниже блок в разметке, тем выше он в стопке. Управлять порядком наложения блоков мы как раз и можем при помощи z — index .

Подсказки

Скопировать ссылку «Подсказки» Скопировано

�� z — index срабатывает для элементов с позиционированием (свойство position ), отличающимся от статичного (значения relative , absolute , fixed , sticky ).

�� Исключение из правил: z — index работает с элементами, у которых значение свойства opacity меньше 1. Например, трюк с opacity : 0 . 999 почти не повлияет на внешний вид, но позволит использовать z — index без изменения позиционирования элемента.

�� z — index также срабатывает у флекс и грид-элементов и везде, где создаётся контекст наложения.

�� Если z — index не указан, то блоки накладываются друг на друга в том порядке, в котором указаны в разметке. Чем ниже в разметке, тем выше в стопке. А если указан, то стопка блоков формируется согласно значению этого свойства.

На практике

Скопировать ссылку «На практике» Скопировано

Алёна Батицкая советует

Скопировать ссылку «Алёна Батицкая советует» Скопировано

�� Часто вижу такие записи z — index : 99999 . Видимо, это нужно чтобы совершенно точно блок был поверх всего. Но обычно это избыточно и может привести к неожиданным последствиям в процессе поддержки сайта. Я обычно проставляю значения -1, 0 и 1. А если нужно что-то большее, то значения 10 будет вполне достаточно.

CSS свойство z-index не работает

Я задал родителю значение свойства positon: static; для дочернего допустим menu1 и logo поставил absolute. и разные z-index. и все равно они как бы находятся на одной плоскости, а не как обещано с z-index в разных.

Отслеживать
задан 25 фев 2013 в 13:36
317 3 3 золотых знака 8 8 серебряных знаков 23 23 бронзовых знака

Как они могу быть на одной плоскости если у них разные z-index? Тем более что их position: absolute вынесло из нормального потока. jsfiddle.net/dCtnX

25 фев 2013 в 13:38
не помогает(
25 фев 2013 в 13:45

все)))я оказывается все правильно сделал. просто когда два класса вместе указывал ошибку допустил)спасибо)

25 фев 2013 в 13:51
Какого результата Вы хотите добиться?
25 фев 2013 в 13:52
нет я результата добился)))спасибо))за оказанную помощь
25 фев 2013 в 14:17

1 ответ 1

Сортировка: Сброс на вариант по умолчанию

вот очень годная статья про z-index-ы

Отслеживать
ответ дан 25 фев 2013 в 14:01
actionless actionless
1,381 8 8 серебряных знаков 7 7 бронзовых знаков

    Важное на Мете
Похожие

Подписаться на ленту

Лента вопроса

Для подписки на ленту скопируйте и вставьте эту ссылку в вашу программу для чтения RSS.

Дизайн сайта / логотип © 2023 Stack Exchange Inc; пользовательские материалы лицензированы в соответствии с CC BY-SA . rev 2023.10.27.43697

Нажимая «Принять все файлы cookie» вы соглашаетесь, что Stack Exchange может хранить файлы cookie на вашем устройстве и раскрывать информацию в соответствии с нашей Политикой в отношении файлов cookie.

4 reasons your z-index isn’t working (and how to fix it)

4 reasons your z-index isn’t working (and how to fix it)

Z-index is a CSS property that allows you to position elements in layers on top of one another. It’s super useful, and honestly a very important tool to know how to use in CSS.

Unfortunately, z-index is one of those properties that doesn’t always behave in an intuitive way. It seems simple at first- a higher z-index number means the element will be on top of elements with lower z-index numbers. But there are some additional rules that make things more complicated. And you can’t always fix things by setting the z-index to 999999! ?

This article will explain in detail four of the most common reasons that z-index isn’t working for you, and exactly how you can fix it.

We’ll be going through some actual code examples and problem-solving them. After reading this article, you’ll be able to understand and avoid those common z-index pitfalls!

NlDhNhhBXrXmR35aZCt4XCGbfBCt4bRPLHzK

Now, the next thing we want to do is rotate the bottom cat upside down, using the transform property. That way, both cats will be underneath the white block, with only their heads sticking out.

But doing so can cause more z-index -related confusion. We’ll address the problem and the solution in the next part.

3. Setting some CSS properties like opacity or transform will put the element in a new stacking context.

As we just mentioned, we want to turn the bottom cat upside down. To accomplish this, we’ll add transform: rotate(180deg) .

.cat-bottom

But this causes the bottom cat to be displayed on top of the white block again!

GTJjexmzYUkJa37hDuIUALqGngUjSl0wxFcE

What the heck is going on here??

You may not run into this issue often, but another aspect of stacking order is that some CSS properties like transform or opacity will put the element into its own, new stacking context.

What this means is that adding the transform to the .cat-bottom element makes it behave as if it had a z-index of 0. Even though it doesn’t have its position or z-index set at all! (W3.org has some informative but rather dense documentation on how this works with the opacity property)

Remember, we never added a z-index value to the white block, only position: relative . This was enough to position the white block on top of the unpositioned cats.

But since the .bottom-cat element is acting as though it is relatively positioned with z-index: 0 , transforming it has positioned it on top of the white block.

The solution to this is to set position: relative and explicitly set z-index on at least the white block. You could go one step further and set position: relative and a lower z-index on the cat elements, just to be extra safe.

.content__block < position: relative; z-index: 2; >.cat-top, .cat-bottom

In my opinion, doing this will solve most, if not all of the more basic z-index issues.

Now, let’s move on to our last reason that your z-index isn’t working. This one is a bit more complex, because it involves parent and child elements.

4. The element is in a lower stacking context due to its parent’s z-index level

Let’s check out our code example for this:

Here’s what we have: a simple webpage with regular content, and a pink side tab that says “Send Feedback” that is positioned on top of the content.

Then, when you click on the photo of the cat, a modal window with a transparent gray background overlay opens up.

However, even when the modal window is open, the side tab is still on top of the gray overlay. We want the overlay to be displayed over everything, including the side tab.

Let’s take a look at the CSS for the elements in question:

.content < position: relative; z-index: 1; >.modal < position: fixed; z-index: 100; >.side-tab

All the elements have their position set, and the side tab has a z-index of 5, which positions it on top of the content element, which is at z-index: 1 .

Then, the modal has z-index: 100 which should put it on top of the side tab at z-index: 5 . But instead, the modal overlay is underneath the side tab.

Why is this happening?

Previously, we addressed some factors that go into the stacking context, such as if the element has its position set, as well as its order in the markup.

But yet another aspect of stacking context is that a child element is limited to the stacking context of its parent.

Let’s take a closer look at the three elements in question.

Here’s the markup we have:

Looking at the markup, we can see that the content and side tab elements are siblings. That is, they exist at the same level in the markup (this is different from z-index level). And the modal is a child element of the content element.

Because the modal is inside the content element, its z-index of 100 only has an effect inside its parent, the content element. For example, if there were other child elements that were siblings to the modal, their z-index values would put them on top of or underneath each other.

But the z-index value of those child elements doesn’t mean anything outside the parent, because the parent content element has its z-index set to 1.

So its children, including the modal, can’t break out of that z-index level.

(You can remember it with this slightly depressing metaphor: a child can be limited by its parents, and can’t break free of them.)

There are a couple of solutions to this problem:

Solution: Move the modal outside of the content parent, and into the main stacking context of the page.

The corrected markup would then look like this:

Now, the modal element is a sibling element to the two others. This puts all three elements in the same stacking context as them, so each of their z-index levels will now affect one another.

In this new stacking context, the elements will display in the following order, from top to bottom:

  • modal ( z-index: 100 )
  • side tab ( z-index: 5 )
  • content ( z-index: 1 )

Alternative Solution: Remove positioning from the content, so it won’t limit the modal’s z-index.

If you don’t want to or can’t change the markup, you can fix this problem by removing the position setting from the content element:

.content < // No position set >.modal < position: absolute; z-index: 100; >.side-tab

Since the content element is now unpositioned, it will no longer limit the modal’s z-index value. So the open modal will be positioned on top of the side tab element, due to its higher z-index of 100.

While this does work, I personally would go for the first solution.

Because if for some reason in the future you have to position the content element, it will again limit the modal’s order in the stacking context.

In Summary

I hope that you’ve found this tutorial helpful! To sum up, most issues with z-index can be solved by following these two guidelines:

  1. Check that the elements have their position set and z-index numbers in the correct order.
  2. Make sure that you don’t have parent elements limiting the z-index level of their children.
Want more?

I’m creating a course in responsive design! Sign up here to get emailed when it’s published.

I write web development tutorials on my blog coder-coder.com, post mini-tips on Instagram and coding tutorials on YouTube.

Почему не работает z-index?

Почему не работает z-index у .sub-menu1?
Нужно, чтобы меню выезжало из под header.

.container < width: 1140px; margin: 0 auto; >.clearfix::after < content: ""; display: table; clear: both; >.header < width: 100%; height: 108px; background-color: #262626; margin: 0; position: relative; z-index: 1; >.logo < width: 143px; height: 100%; float: left; background: url("logo.png") no-repeat 50% 50%; >.menu-right < width: 143px; height: 100%; float: right; line-height: 108px; text-align: center; >.menu-center < height: 100%; margin-left: 153px; line-height: 108px; padding-left: 89px; >.submenu1 < display: block; width: 100%; height: 80px; background-color: grey; overflow: hidden; position: absolute; left: 0; top: 28px; transition: 1s; z-index: 100; >.men1:hover + .submenu1
  • Вопрос задан более трёх лет назад
  • 15749 просмотров

1 комментарий

Оценить 1 комментарий

Твой код: https://jsfiddle.net/vbn3hp5w/
А что должно было быть?
Решения вопроса 0
Ответы на вопрос 2

Сделайте одинаковый position у header и submenu1.
Было похожая проблема, решил, поставив одинаковое значение свойства position.

Ответ написан более трёх лет назад
Нравится 6 1 комментарий
Ты меня просто выручил!
devstudent @devstudent
frontend-developer

потому что оно внутри header ваше субменю, у него не может быть индекс выше , чем у родителя, хоть 100500 выставьте, не сработает, только выше чем у других элеметнов того же уровня, что и субменю.

Ответ написан более трёх лет назад
Нравится 2 6 комментариев
алексей @tolval Автор вопроса

Но если вынести из родителя, то как его через hover на ссылку в меню зацепить?
Вывел div после header, но он все-равно перекрывает.

devstudent @devstudent

алексей: в таких случаях цепляют ховер джаваскриптом. но вы попробуйте сначала расставить z-индексы внтури хидера, может получится

алексей @tolval Автор вопроса

devstudent: По поводу самой меню наверное и правда придется другими методами. Но почему перекрывает все-равно не пойму. Поставил div вообще отдельно, то есть у него родитель общий с хидером, поставил всем блокам в хидере z-index: 1 и relative. И без толку, не реагирует.

devstudent @devstudent

ну если див ВНЕ хидера, то поставьте ему z-индекс ВЫШЕ чем у хидера. какой смысл ставить одинаковые z-index: 1 тогда. тогда выше будет тот элемент, чкто ниже в дереве DOM.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *