Home >Web Front-end >CSS Tutorial >Can CSS Selectors Target Elements Based on Class Prefix?

Can CSS Selectors Target Elements Based on Class Prefix?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-30 11:21:22880browse

Can CSS Selectors Target Elements Based on Class Prefix?

CSS Selectors by Class Prefix

Question:

Is it feasible to apply a CSS rule to elements where at least one class starts with a specified prefix? For instance, suppose we have the following HTML snippet:

<div>

Can we apply a rule that targets only divs with classes starting with "status-"?

Answer:

CSS 2.1:

In CSS 2.1, this is not possible.

CSS 3:

CSS3 introduced attribute substring-matching selectors that make this possible:

div[class^="status-"], div[class*=" status-"]
  • [class^="status-"] matches elements where the class attribute starts with "status-".
  • [class*=" status-"] matches elements where the class attribute contains "status-" directly after a space character (ensuring it's not part of another word).

Note that the latter selector includes an intentional space character, as class names are typically separated by spaces. This checks any other classes in the element's class attribute and also handles cases where class attributes are space-padded.

If you can guarantee that your markup will never have elements where the status prefix is embedded within another word, you could simplify the selector to [class*="status-"]. However, for robustness, the combination of both selectors is recommended.

Alternatively, if you have control over the HTML generation, it might be easier to create a dedicated "status" class with the desired prefix.

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