Targeting Elements with Attributes of Any Value in CSS
In CSS, it's often necessary to target elements based on their attributes. While it's straightforward to select elements with specific attribute values, targeting elements with arbitrary attribute values can be more challenging.
Question: Selecting Elements with Arbitrary Attributes
How can we target elements that have an attribute of any value (except when the attribute hasn't been added to the element)? For instance, we want to target any anchor tag with a value for the "rel" attribute.
Answer: Using the Attribute Selector with an Empty Value
To achieve this, we can use the attribute selector with an empty value. The following CSS rule targets any anchor tag with a "rel" attribute defined:
a[rel] { color: red; }
This rule will match the first and third anchor tags in the following HTML:
<a href="#" rel="eg">red text</a> <a href="#">standard text</a> <a href="#" rel="more">red text again</a>
Update: Distinguishing Between Empty and Non-Empty Values
In certain cases, it may be necessary to differentiate between elements with an empty attribute value and those with a non-empty value. To do this, we can use the CSS ":not" pseudo-class:
a[rel]:not([rel=""]) { color: red; }
This rule will only target anchor tags with non-empty "rel" attribute values.
The above is the detailed content of How Can I Target CSS Elements with Attributes of Any Value?. For more information, please follow other related articles on the PHP Chinese website!