Home > Web Front-end > CSS Tutorial > Can CSS Select Elements Based on Class Prefixes?

Can CSS Select Elements Based on Class Prefixes?

Barbara Streisand
Release: 2024-12-29 08:18:13
Original
512 people have browsed it

Can CSS Select Elements Based on Class Prefixes?

Is Prefix-Based CSS Class Selection Possible?

In the realm of web development, it's often necessary to apply CSS rules to elements based on specific class prefixes. For instance, you may want to target elements whose classes begin with the "status-" prefix.

Can't Do it with CSS2.1

Unfortunately, CSS2.1 does not provide any direct way to achieve prefix-based class selection. However, CSS3 attribute substring-matching selectors come to our rescue.

Prefix-Based Selection with CSS3

CSS3 introduces two attribute selectors that can help us:

[class^="status-"], div[class*=" status-"]
Copy after login

Breakdown of the Selectors:

  • [class^="status-"] - Matches elements whose class attribute starts with "status-".
  • [class*=" status-"] - Matches elements whose class attribute contains "status-" within a whitespace-separated string.

Combining these two selectors ensures that we catch all appropriate elements, even those with multiple space-separated classes.

Another Gotcha

Note that simply using [class*="status-"] may also match elements like:

<div>
Copy after login
Copy after login

To avoid this, it's best to combine the two selectors as shown above.

Other Options

If you have control over the HTML markup, a simpler approach is to separate the status prefix into its own class, such as:

<div>
Copy after login
Copy after login

This allows you to target elements with [class="status-important"].

The above is the detailed content of Can CSS Select Elements Based on Class Prefixes?. 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