Home  >  Article  >  Web Front-end  >  How Can I Target CSS Elements with Attributes of Any Value?

How Can I Target CSS Elements with Attributes of Any Value?

Barbara Streisand
Barbara StreisandOriginal
2024-11-24 12:33:40370browse

How Can I Target CSS Elements with Attributes of Any Value?

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!

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