Please note, this is a STATIC archive of website developer.mozilla.org from 03 Nov 2016, cach3.com does not collect or store any user information, there is no "phishing" involved.

Контекст наложения (stacking context)

Эта статья нуждается в техническом обзоре. Как вы можете помочь.

Эта статья нуждается в редакционном обзоре. Как вы можете помочь.

Перевод не завершен. Пожалуйста, помогите перевести эту статью с английского.

Контекст наложения (stacking context) это концепция трехмерного разположения HTML элементов вдоль оси Z , по отношению к пользователю, находящемуся перед экраном.  HTML элементы занимают это место по порядку, основанному на атрибутах элемента.

« CSS « Understanding CSS z-index

Контекст наложения

 

В предыдущем примере  Добавляем z-index, порядок отображения определенных DIVs элементов зависел от их z-index значения. Это возникает благодаря тому, что у этих элементов есть специальные свойства, которые заставляют их формировать контекст наполнения ( stacking context ).

Контекст может формироваться в любом месте документа, любым элементом, у которого выполняется одно из следующих условий: 

  • является корневым элементом (HTML),
  • позиционирован абсолютно (position:absolute) или относительно (position:relative) с z-index значением отличным от "auto",
  • flex элемент с z-index отличным от  "auto", чей родительский элемент имеет свойство display: flex|inline-flex,
  • элементы с  opacity меньше чем 1. (См. the specification for opacity),
  • элементы с  transform отличным от "none",
  • элементы с mix-blend-mode значением отличным от "normal",
  • elements with a filter value other than "none",
  • элементы с isolation установленным в  "isolate",
  • position: fixed
  • если мы указываем элементу атрибут  will-change при этом не обязательно присваивать ему значения (См. this post)
  • элементы с -webkit-overflow-scrolling установленым в "touch"

Внутри контекста наложения, Within a stacking context, дочерние элементы расположены в соответствии с правилами, описанными ранее. Важно заметить, что значения свойства z-index для дочерних элементов формирующих конекст наложения, будут учитываться только в рамках родительского элемента. Stacking contexts are treated atomically as a single unit in the parent stacking context.

Суммируем:

  • Позиционирование и присваивание HTML элементам свойства z-index создает контекст наложения, (так же как и присваивание элементу opacity меньше 1).
  • Контексты наложения могут быть частью других контекстов наложения и вместе создавать иерархию контекстов наложения. 
  • Каждый контекст наложения абсолютно независим от своего соседа: только подчиненные элементы учитываются при обработке наложения.
  • Each stacking context is self-contained: after the element's contents are stacked, the whole element is considered in the stacking order of the parent stacking context.
Note: The hierarchy of stacking contexts is a subset of the hierarchy of HTML elements, because only certain elements create stacking contexts. We can say that elements that do not create their own stacking contexts are assimilated by the parent stacking context.

The example

Example of stacking rules modified using z-index

In this example every positioned element creates its own stacking context, because of their positioning and z-index values. The hierarchy of stacking contexts is organized as follows:

  • Root
    • DIV #1
    • DIV #2
    • DIV #3
      • DIV #4
      • DIV #5
      • DIV #6

It is important to note that DIV #4, DIV #5 and DIV #6 are children of DIV #3, so stacking of those elements is completely resolved within DIV#3. Once stacking and rendering within DIV #3 is completed, the whole DIV #3 element is passed for stacking in the root element with respect to its sibling's DIV.

Notes:

  • DIV #4 is rendered under DIV #1 because DIV #1's z-index (5) is valid within the stacking context of the root element, while DIV #4's z-index (6) is valid within the stacking context of DIV #3. So, DIV #4 is under DIV #1, because DIV #4 belongs to DIV #3, which has a lower z-index value.
  • For the same reason DIV #2 (z-index 2) is rendered under DIV#5 (z-index 1) because DIV #5 belongs to DIV #3, which has an higher z-index value.
  • DIV #3's z-index is 4, but this value is independent from z-index of DIV #4, DIV #5 and DIV #6, because it belongs to a different stacking context.
  • An easy way to figure out the rendering order of stacked elements along the Z axis is to think of it as a "version number" of sorts, where child elements are minor version numbers underneath their parent's major version numbers. This way we can easily see how an element with a z-index of 1 (DIV #5) is stacked above an element with a z-index of 2 (DIV #2), and how an element with a z-index of 6 (DIV #4) is stacked below an element with a z-index of 5 (DIV #1). In our example (sorted according to the final rendering order):
    • Root
      • DIV #2 - z-index is 2
      • DIV #3 - z-index is 4
        • DIV #5 - z-index is 1, stacked under an element with a z-index of 4, which results in a rendering order of 4.1
        • DIV #6 - z-index is 3, stacked under an element with a z-index of 4, which results in a rendering order of 4.3
        • DIV #4 - z-index is 6, stacked under an element with a z-index of 4, which results in a rendering order of 4.6
      • DIV #1 - z-index is 5

Example Source Code

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="en">
  <head>

    <title>Understanding CSS z-index: The Stacking Context: Example Source</title>

    <style type="text/css">
      * {
        margin: 0;
        }
      html {
        padding: 20px;
        font: 12px/20px Arial, sans-serif;
        }
      div {
        opacity: 0.7;
        position: relative;
        }
      h1 {
        font: inherit;
        font-weight: bold;
        }
      #div1, #div2 {
        border: 1px dashed #696;
        padding: 10px;
        background-color: #cfc;
        }
      #div1 {
        z-index: 5;
        margin-bottom: 190px;
        }
      #div2 {
        z-index: 2;
        }
      #div3 {
        z-index: 4;
        opacity: 1;
        position: absolute;
        top: 40px;
        left: 180px;
        width: 330px;
        border: 1px dashed #900;
        background-color: #fdd;
        padding: 40px 20px 20px;
        }
      #div4, #div5 {
        border: 1px dashed #996;
        background-color: #ffc;
        }
      #div4 {
        z-index: 6;
        margin-bottom: 15px;
        padding: 25px 10px 5px;
        }
      #div5 {
        z-index: 1;
        margin-top: 15px;
        padding: 5px 10px;
        }
      #div6 {
        z-index: 3;
        position: absolute;
        top: 20px;
        left: 180px;
        width: 150px;
        height: 125px;
        border: 1px dashed #009;
        padding-top: 125px;
        background-color: #ddf;
        text-align: center;
        }
    </style>

  </head>
  <body>

    <div id="div1">
      <h1>Division Element #1</h1>
      <code>position: relative;<br/>
      z-index: 5;</code>
    </div>

    <div id="div2">
      <h1>Division Element #2</h1>
      <code>position: relative;<br/>
      z-index: 2;</code>
    </div>

    <div id="div3">

      <div id="div4">
        <h1>Division Element #4</h1>
        <code>position: relative;<br/>
        z-index: 6;</code>
      </div>

      <h1>Division Element #3</h1>
      <code>position: absolute;<br/>
      z-index: 4;</code>

      <div id="div5">
        <h1>Division Element #5</h1>
        <code>position: relative;<br/>
        z-index: 1;</code>
      </div>
   
      <div id="div6">
        <h1>Division Element #6</h1>
        <code>position: absolute;<br/>
        z-index: 3;</code>
      </div>

    </div>

  </body>
</html>

Division Element #1

position: relative;
z-index: 5;

Division Element #2

position: relative;
z-index: 2;

Division Element #3

position: absolute;
z-index: 4;

Division Element #4

position: relative;
z-index: 6;

Division Element #5

position: relative;
z-index: 1;

Division Element #6

position: absolute;
z-index: 3;

See also

Original Document Information

Метки документа и участники

 Внесли вклад в эту страницу: lerniri
 Обновлялась последний раз: lerniri,