Home >Web Front-end >CSS Tutorial >Can You Apply Multiple :before Pseudo-Elements to the Same Element?

Can You Apply Multiple :before Pseudo-Elements to the Same Element?

DDD
DDDOriginal
2024-11-09 22:01:02826browse

Can You Apply Multiple :before Pseudo-Elements to the Same Element?

Can Multiple :before Pseudo-Elements Exist for the Same Element?

Question:

Is it possible to apply multiple :before pseudo-elements to the same element? For example:

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

Answer:

No, CSS2.1 specifies that an element can only have one of any kind of pseudo-element at any given time. This means that while an element can have both a :before and an :after pseudo-element, it cannot have more than one of each type.

As a result, when multiple :before rules target the same element, they are cascaded into a single :before pseudo-element. For example, the above code collapses to:

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

Only the last content declaration, which has the highest precedence, takes effect.

Workarounds:

If you want to apply multiple :before pseudo-elements to the same element, you can use combined selectors to specify exactly what the browser should do. For instance:

.circle.now:before {
    content: "○";
}
.circle.now:hover:before {
    background: #ccc;
}

This will create two :before pseudo-elements with different content and styling.

The above is the detailed content of Can You Apply Multiple :before Pseudo-Elements to the Same 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