CSS for Web Development

0% completed

Previous
Next
Z-index

Lesson: Z-index

The z-index property controls the stacking order of positioned elements. It determines which element sits on top when elements overlap. This property is especially useful when using positioning (like absolute or fixed) to create complex layouts.

Image

A higher z-index value means the element will be closer to the front, while a lower value means it will be further back. Remember, z-index only works on elements that have a position value other than static.

Syntax

Follow the code block below to set z-index in CSS:

/* Set z-index for a positioned element */ z-index: value; /* e.g., z-index: 10; */

Explanation:

  • z-index:
    • A numerical value that determines the stacking order of elements.
    • Only applies to elements with a positioning value (relative, absolute, fixed, or sticky).
    • Higher values place elements on top of those with lower values.
Image

Example 1: Overlapping Elements with Different Z-index Values

In this example, we create two overlapping <div> elements. We use z-index to control which element appears on top.

HTML

. . . .

Explanation:

  • Box 1 (.box1):
    • Has a z-index of 1, which places it behind Box 2.
  • Box 2 (.box2):
    • Has a z-index of 2, so it appears in front of Box 1.
  • Outcome:
    • Although they overlap, the light blue Box 2 is displayed on top due to its higher z-index.

Example 2: Z-index in a Complex Layout

In this example, we create a header, content area, and a floating sidebar. The sidebar overlaps the content. We use z-index to ensure the sidebar appears over the content but below the header.

HTML

. . . .

Explanation:

  • Header (.header):
    • Uses position: fixed and a high z-index: 3 so it stays on top of other elements.
  • Sidebar (.sidebar):
    • Positioned absolutely with z-index: 2 to overlap the content but remain below the header.
  • Content (.content):
    • Has a lower z-index: 1 so it stays behind the sidebar.
  • Outcome:
    • The header appears on top, the sidebar is in the middle, and the main content remains at the bottom of the stacking order.

This lesson shows how the z-index property is used to control the stacking order of overlapping elements. By adjusting the z-index values, you can manage which elements appear on top in your layout.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next