Home > Web Front-end > CSS Tutorial > How Can I Position a CSS Pseudo-Element Below Its Parent Element?

How Can I Position a CSS Pseudo-Element Below Its Parent Element?

Linda Hamilton
Release: 2024-12-26 06:03:14
Original
509 people have browsed it

How Can I Position a CSS Pseudo-Element Below Its Parent Element?

Positioning Pseudo-Elements Beneath Their Parent Element

In CSS, pseudo-elements are typically positioned relative to their parent element. However, attempts to place them below their parent using z-index values may seem ineffective.

Creating a Stacking Context for Pseudo-Elements

To overcome this limitation, pseudo-elements must be positioned within a new stacking context. This is achieved by:

  • Setting the position property to absolute or fixed for the pseudo-element.
  • Assigning a non-auto value to the pseudo-element's z-index.

Example:

Consider the following code:

#element {
    position: relative;
    z-index: 1;
}
#element::after {
    content: " ";
    position: absolute;
    z-index: 0;
    width: 100px;
    height: 100px;
}
Copy after login

Initially, the #element::after pseudo-element is positioned above its parent element. To change this order:

#element {
    position: relative;
    width: 100px;
    height: 100px;
    background-color: blue;
}

#element::after {
    content: "";
    width: 150px;
    height: 150px;
    background-color: red;
    
    /* Positioning and creating a stacking context */
    position: absolute;
    z-index: -1;
}
Copy after login

By adding position: absolute and z-index: -1 to the pseudo-element, a new stacking context is created. This shifts the pseudo-element below its parent element while maintaining its relative position within the context.

The above is the detailed content of How Can I Position a CSS Pseudo-Element Below Its Parent Element?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template