Home > Web Front-end > CSS Tutorial > Can Multiple :before Pseudo-elements be Applied to a Single HTML Element?

Can Multiple :before Pseudo-elements be Applied to a Single HTML Element?

Mary-Kate Olsen
Release: 2024-11-15 22:17:03
Original
810 people have browsed it

Can Multiple :before Pseudo-elements be Applied to a Single HTML Element?

Multiple :before Pseudo-elements: A Restrictions Overview

Question:

Can multiple :before pseudo-elements be applied to a single HTML element?

Answer:

Unfortunately, it is not possible to have multiple :before pseudo-elements for the same element in CSS2.1. An element can have only one of any kind of pseudo-element at a time, including :before and :after.

Explanation:

When multiple :before rules apply to the same element, they cascade and merge into a single :before pseudo-element. Only the top-most rule, with the highest precedence, has its declarations applied. This is consistent with how the cascade works for regular CSS properties.

Therefore, in your example:

.circle:before {
    content: "CF";
    font-size: 19px;
}
.now:before{
    content: "Now";
    font-size: 19px;
    color: black;
}
Copy after login

Only the second rule will be applied, and the output will be:

.circle.now:before {
    content: "Now";
    font-size: 19px;
    color: black;
}
Copy after login

Alternative Approaches:

To overcome this limitation, you can either:

  • Combine multiple rules into a single selector, such as .circle.now:before, which would apply both rules to the element.
  • Use a CSS preprocessor like Sass or Less, which allows you to nest selectors and create multiple :before pseudo-elements for the same element.

The above is the detailed content of Can Multiple :before Pseudo-elements be Applied to a Single HTML 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