Home >Web Front-end >CSS Tutorial >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-"]
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!