CSS от А до Я: свойство z-index. Свойство позиционирования z-index в CSS Так что же это за свойство

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.

The source for this interactive example is stored in a GitHub repository. If you"d like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.

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: unset;

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

Values

auto The box does not establish a new local stacking context. The stack level of the generated box in the current stacking context is the same as its parent"s box. This that represents a whole number, whether positive or negative. Integers can be used in numerous CSS properties, such as column-count, counter-increment, grid-column, grid-row, and z-index."> is the stack level of the generated box in the current stacking context. The box also establishes a local stacking context in which its stack level is 0 . This means that the z-indexes of descendants are not compared to the z-indexes of elements outside this element.

Formal syntax

auto CSS data type is a special type of that represents a whole number, whether positive or negative. Integers can be used in numerous CSS properties, such as column-count, counter-increment, grid-column, grid-row, and z-index.">

Examples

HTML

Dashed box Gold box Green box

CSS

.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

Specification Status Comment
CSS Transitions
The definition of "animation behavior for z-index" in that specification.
Working Draft Defines z-index as animatable.
CSS Level 2 (Revision 1)
The definition of "z-index" in that specification.
Recommendation Initial definition
Initial value auto
Applies to positioned elements
Inherited no
Media visual
Computed value as specified
Animation type an CSS data type are interpolated via integer discrete steps. The calculation is done as if they were real, floating-point numbers and the discrete value is obtained using the floor function.">integer
Canonical order the unique non-ambiguous order defined by the formal grammar
Creates stacking context yes

Browser compatibility

The compatibility table in this page is generated from structured data. If you"d like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

Update compatibility data on GitHub

Desktop Mobile
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
z-index Chrome Full support 1 Edge Full support 12 Firefox Full support 1 IE Full support 4 Opera Full support 4 Safari Full support 1
Negative values Chrome Full support 1 Edge Full support 12 Firefox Full support 3 IE Full support 4 Opera Full support 4 Safari Full support 1 WebView Android Full support Yes Chrome Android Full support Yes Firefox Android Full support 4 Opera Android Full support Yes Safari iOS Full support Yes Samsung Internet Android Full support Yes

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

Краткая информация

Обозначения

Описание Пример
<тип> Указывает тип значения. <размер>
A && B Значения должны выводиться в указанном порядке. <размер> && <цвет>
A | B Указывает, что надо выбрать только одно значение из предложенных (A или B). normal | small-caps
A || B Каждое значение может использоваться самостоятельно или совместно с другими в произвольном порядке. width || count
Группирует значения. [ crop || cross ]
* Повторять ноль или больше раз. [,<время>]*
+ Повторять один или больше раз. <число>+
? Указанный тип, слово или группа не является обязательным. inset?
{A, B} Повторять не менее A, но не более B раз. <радиус>{1,4}
# Повторять один или больше раз через запятую. <время>#
×

Значения

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

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

Пример

Порядок карт

В данном примере при наведении курсора на карту она выходит на передний край, частично перекрывая остальные собой остальные изображения (рис. 1).

Рис. 1. Изменение порядка карт

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

Объект .style.zIndex

Примечание

Список, созданный с помощью в IE6

В Internet Explorer 6, элемент появляется первым в обычном порядке слоев, и получает значение z-index, равное «1» , наряду со значением свойства position , равному relative . Коричневый блок, появляется вторым, в порядке слоев, и ему назначено свойство z-index, равное «9999» . В соответствии с правилом обычного порядка слоев, и назначенных свойств z-index, коричневый блок должен перекрыть элемент , перекрывает коричневый блок, игнорируя обычный порядок слоев и свойства z-index.

Этот баг в IE6 создает проблемы с выпадающим меню, которое не может перекрыть элементы , а затем, снова его отображать, после того, как выпадающее меню скроется. Другое решение предполагает использование