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

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

Barbara Streisand
Release: 2024-11-24 12:33:40
Original
440 people have browsed it

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;
}
Copy after login

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>
Copy after login

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;
}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template