What is CSS z-index

Home Forums Web Design CSS What is CSS z-index

  • This topic is empty.
  • Creator
    Topic
  • #6378
    designboyo
    Keymaster
      Up
      0
      Down
      ::

      The z-index property in CSS controls the stacking order of elements that overlap each other. When you have multiple elements that are positioned on top of each other, z-index determines which one appears in front and which one appears behind.

      Here’s a basic rundown of how z-index works:

      1. Positioning Context: For z-index to have any effect, the element must have a positioning value other than static (e.g., relative, absolute, fixed, or sticky).
      2. Stacking Order: Elements with higher z-index values are placed in front of elements with lower z-index values. For example:
        css
        .element1 {
        position: absolute;
        z-index: 10;
        }
        .element2 {
        position: absolute;
        z-index: 5;
        }

        In this case, .element1 will be in front of .element2 because it has a higher z-index value.

      3. Default Value: The default value of z-index is auto, which means it will follow the stacking order based on the document flow and the position property. An auto value does not explicitly layer the element above or below others with different z-index values.
      4. Stacking Context: Each positioned element creates a new stacking context. Elements within the same stacking context are ordered according to their z-index values, but stacking contexts themselves can be nested. This means that an element in one stacking context can appear in front of or behind elements in another stacking context based on their respective z-index values and their own stacking contexts.

      Here’s a visual example:

      html
      <div class="container">
      <div class="box1"></div>
      <div class="box2"></div>
      <div class="box3"></div>
      </div>
      css

      .container {
      position: relative;
      }

      .box1, .box2, .box3

      {
      position: absolute;
      width: 100px;
      height: 100px;
      }
      .box1 {
      background: red;
      z-index: 1;
      }
      .box2 {
      background: blue;
      z-index: 3;
      }
      .box3 {
      background: green;
      z-index: 2;
      }

      In this example, the stacking order of .box1, .box2, and .box3 will be:

      1. .box2 (highest z-index of 3)
      2. .box3 (middle z-index of 2)
      3. .box1 (lowest z-index of 1)
    Share
    • You must be logged in to reply to this topic.
    Share