Home >Web Front-end >CSS Tutorial >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-"]
Breakdown of the Selectors:
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>
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>
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!