Using Attribute Selectors

Using attribute selectors

Elements can have attributes that provide extra details.

The following example shows an href attribute in an a (link) tag:

<a href="https://google.com">This is a link</a>

We use CSS attribute selectors to target such elements with their specific attributes. For example:

a[href="https://www.google.com"] {
  color: #FFFF00;
}

Here, we have an exact match selection that selects links with the exact href value of “https://www.google.com”.

Let’s learn how to use these very useful selectors!

Types of attribute selectors

There are several different types of attribute selectors. They’re classified as either presence and value selectors or substring matching selectors. The syntax for each selector begins with the particular attribute name and ends with an equal sign (=), followed by the attribute value(s). The selector type sits between the attribute name and the equal sign .

Presence and value selectors

These selectors select an element based on the existence of an attribute (for example, href) or various matches against the attribute’s value.

The [attr] signifies an attribute and matches any elements with a given attribute name, such as a[title].

The [attr=”value”] refers that the attribute has this exact value and matches all elements with a given attribute name (for example, attr) with a value that’s exactly the value specified (the string inside the quotes). Take a[href="https://www.google.com"], for example:

Get hands-on with 1400+ tech skills courses.