Home >Web Front-end >CSS Tutorial >How Can I Select CSS Elements Based on Class Prefixes?
Attribute-Based CSS Selectors for Class Prefixes
In CSS, identifying elements based on class prefixes can be a perplexing task. Consider the scenario where you wish to apply a rule to any element whose class begins with a specific prefix, such as "status-".
CSS Compatibility
Regrettably, CSS 2.1 lacks the necessary selectors for this task. However, CSS3 introduces attribute substring-matching selectors, which open up new possibilities.
CSS3 Attribute Selectors
The CSS3 attribute selectors that can tackle this challenge are:
Combination of Selectors
To capture all desired elements, you must combine these two selectors:
div[class^="status-"], div[class*=" status-"]
This combination ensures that elements with classes starting with "status-" and elements with a "status-" substring following a whitespace character are both selected.
Cautions and Alternatives
Keep in mind that the [class*="status-"] selector can match undesirable elements if your HTML includes classes like "foo-status-bar". To avoid this, make sure such scenarios are impossible.
Alternatively, if you have control over the HTML or application generating the markup, it may be more straightforward to create a dedicated "status" class with its own prefix. This simplifies the process and ensures consistency.
The above is the detailed content of How Can I Select CSS Elements Based on Class Prefixes?. For more information, please follow other related articles on the PHP Chinese website!