Home >Web Front-end >CSS Tutorial >Can CSS Pseudo-elements Be Positioned Below Their Parent Element?

Can CSS Pseudo-elements Be Positioned Below Their Parent Element?

Linda Hamilton
Linda HamiltonOriginal
2024-12-23 22:59:12307browse

Can CSS Pseudo-elements Be Positioned Below Their Parent Element?

CSS Stacking Order: Can Pseudo-elements Be Positioned Below Parent Elements?

When styling an element using the :after pseudo-element, it may appear that the pseudo-element always sits above the parent element. This is because pseudo-elements are inherently treated as descendants of their associated element and inherit the same stacking context.

Solution: Creating a New Stacking Context

To position a pseudo-element below its parent, you need to create a new stacking context. This can be achieved by positioning the pseudo-element absolutely and assigning a z-index value other than "auto."

Consider the following CSS and HTML code:

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

#element::after {
    content: "";
    width: 150px;
    height: 150px;
    background-color: red;

    /* create a new stacking context */
    position: absolute;
    z-index: -1; /* to be below the parent element */
}

Explanation:

  • The #element div is given a relative position to provide a context for absolute positioning.
  • The :after pseudo-element is defined with its content and dimensions.
  • The pseudo-element is positioned absolutely and assigned a negative z-index (-1) to ensure it is placed below the parent element.

With this new stacking context, the :after pseudo-element can now be positioned underneath the #element div, regardless of the parent element's stacking order.

The above is the detailed content of Can CSS Pseudo-elements Be Positioned Below Their Parent Element?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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