z-index

z-index¶

Свойство z-index определяет положение элемента и нижестоящих элементов по оси z. В случае перекрытия элементов, это значение определяет порядок наложения. В общем случае, элементы с большим z-index перекрывают элементы с меньшим.

Для позиционируемого контейнера свойство z-index определяет:

  • порядок наложения в текущем контексте наложения;
  • создаёт ли контейнер локальный контекст наложения.

Демо¶

Синтаксис¶

 1 2 3 4 5 6 7 8 9 10 11 12 13
/* Значение - ключевое слово */ z-index: auto; /* значения */ z-index: 0; z-index: 3; z-index: 289; z-index: -1; /* Отрицательные значения понижают приоритет */ /* Глобальные значения */ z-index: inherit; z-index: initial; z-index: unset; 

Значения¶

В качестве значения используются целые числа (положительные, отрицательные и ноль). Чем больше значение, тем выше находится элемент по сравнению с теми элементами, у которых оно меньше. При равном значении z-index , на переднем плане находится тот элемент, который в коде HTML описан ниже. Допустимо использовать отрицательное значение.

Кроме числовых значений применяется auto — порядок элементов в этом случае строится автоматически, исходя из их положения в коде HTML и принадлежности к родителю, поскольку дочерние элементы имеют тот же номер, что их родительский элемент.

auto Контейнер не будет создавать локального контекста наложения. Уровень контейнера в текущем контексте наложения такой же, как и у родительского. Целое число определяет уровень контейнера в текущем контексте наложения. Контейнер также будет создавать локальный контекст наложения, в котором его собственный уровень будет равен 0 . Это значит, что значения z-index нижестоящих элементов не будут сравниваться с z-индексами элементов вне этого контейнера.

Читайте также:  Как отличить java от kotlin

Значение по-умолчанию: auto

Применяется к позиционированным элементам

Спецификации¶

Пример¶

 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
 html> head> meta charset="utf-8" /> title>Порядок картtitle> style> .card  position: relative; > .three  top: 50px; left: 55px; z-index: 5; > .seven  left: -120px; top: 25px; z-index: 2; > .ace  left: -295px; z-index: 1; > .card:hover  z-index: 10; > style> head> body> img src="image/3.png" alt="3" class="card three" /> img src="image/7.png" alt="7" class="card seven" /> img src="image/ace.png" alt="Туз" class="card ace" /> body> html> 

Источник

z-index

The z-index CSS property sets the z-order of a positioned element and its descendants or flex items. Overlapping elements with a larger z-index cover those with a smaller one.

Try it

For a positioned box (that is, one with any position other than static ), the z-index property specifies:

  1. The stack level of the box in the current stacking context.
  2. Whether the box establishes a local stacking context.

Syntax

/* Keyword value */ z-index: auto; /* values */ z-index: 0; z-index: 3; z-index: 289; z-index: -1; /* Negative values to lower the priority */ /* Global values */ z-index: inherit; z-index: initial; z-index: revert; z-index: revert-layer; z-index: unset; 

The z-index property is specified as either the keyword auto or an .

Values

The box does not establish a new local stacking context. The stack level of the generated box in the current stacking context is 0 .

Formal definition

Formal syntax

Examples

Visually layering elements

HTML

div class="wrapper"> div class="dashed-box">Dashed boxdiv> div class="gold-box">Gold boxdiv> div class="green-box">Green boxdiv> 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; /* put .gold-box above .green-box and .dashed-box */ background: gold; width: 80%; left: 60px; top: 3em; > .green-box  position: absolute; z-index: 2; /* put .green-box above .dashed-box */ background: lightgreen; width: 20%; left: 65%; top: -25px; height: 7em; opacity: 0.9; > 

Result

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jul 18, 2023 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.

Источник

z-index

Любые позиционированные элементы на веб-странице могут накладываться друг на друга в определенном порядке, имитируя тем самым третье измерение, перпендикулярное экрану. Каждый элемент может находиться как ниже, так и выше других объектов веб-страницы, их размещением по z-оси и управляет z-index . Это свойство работает только для элементов, у которых значение position задано как absolute , fixed или relative .

Синтаксис

z-index: число | auto | inherit

Значения

В качестве значения используются целые числа (положительные, отрицательные и ноль). Чем больше значение, тем выше находится элемент по сравнению с теми элементами, у которых оно меньше. При равном значении z-index , на переднем плане находится тот элемент, который в коде HTML описан ниже. Хотя спецификация и разрешает использовать отрицательные значения z-index , но такие элементы не отображаются в браузере Firefox до версии 2.0 включительно.

Кроме числовых значений применяется auto — порядок элементов в этом случае строится автоматически, исходя из их положения в коде HTML и принадлежности к родителю, поскольку дочерние элементы имеют тот же номер, что их родительский элемент. Значение inherit указывает, что оно наследуется у родителя.

HTML5 CSS2.1 IE Cr Op Sa Fx

     #layer1, #layer2, #layer3, #layer4 < position: relative; /* Относительное позиционирование */ >#layer1, #layer3 < font-size: 50px; /* Размер шрифта в пикселах */ color: #000080; /* Синий цвет текста */ >#layer2, #layer4 < top: -55px; /* Сдвигаем текст вверх */ left: 5px; /* Сдвигаем текст вправо */ color: #ffa500; /* Оранжевый цвет текста */ font-size:70px; /* Размер шрифта в пикселах */ >#layer1 < z-index: 2; >#layer2 < z-index: 1; >#layer3 < z-index: 3; >#layer4 

Слой 1 наверху

Слой 4 наверху

Результат данного примера показан на рис. 1.

Применение свойства z-index

Рис. 1. Применение свойства z-index

Объектная модель

[window.]document.getElementById(» elementID «).style.zIndex

Браузеры

Список, созданный с помощью тега , в браузере Internet Explorer 6 всегда отображается поверх других элементов, несмотря на значение z-index .

Internet Explorer до версии 7.0 включительно не поддерживает значение inherit и интерпретирует auto как 0.

В браузере Firefox до версии 2.0 включительно отрицательное значение z-index располагает элемент ниже фона веб-страницы и его контента.

Источник

CSS Layout — The z-index Property

The z-index property specifies the stack order of an element.

The z-index Property

When elements are positioned, they can overlap other elements.

The z-index property specifies the stack order of an element (which element should be placed in front of, or behind, the others).

An element can have a positive or negative stack order:

This is a heading

Because the image has a z-index of -1, it will be placed behind the text.

Example

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

Another z-index Example

Example

Here we see that an element with greater stack order is always above an element with a lower stack order:

.black-box position: relative;
z-index: 1;
border: 2px solid black;
height: 100px;
margin: 30px;
>

.gray-box position: absolute;
z-index: 3;
background: lightgray;
height: 60px;
width: 70%;
left: 50px;
top: 50px;
>

.green-box position: absolute;
z-index: 2;
background: lightgreen;
width: 35%;
left: 270px;
top: -15px;
height: 100px;
>

Without z-index

If two positioned elements overlap each other without a z-index specified, the element defined last in the HTML code will be shown on top.

Example

Same example as above, but here with no z-index specified:

.black-box position: relative;
border: 2px solid black;
height: 100px;
margin: 30px;
>

.gray-box position: absolute;
background: lightgray;
height: 60px;
width: 70%;
left: 50px;
top: 50px;
>

.green-box position: absolute;
background: lightgreen;
width: 35%;
left: 270px;
top: -15px;
height: 100px;
>

CSS Property

Источник

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

Источник

Оцените статью