How to Target HTML Attributes with CSS

Most CSS selectors target elements by their name, class, or ID.

For example, you might style every <p> element or every element with the class .button. Sometimes, though, you need to be more specific.

In such cases you can use attribute selectors.

With an attribute selector you select elements based on whether they have a specific HTML attribute or an attribute holding a specific value.

Using attribute selectors helps you develop CSS that is more focused in what an element does, rather than what the element’s “identity” is.

A basic attribute selector

Let’s see a simple example:

Example of an input using the required attribute.

This selector targets every <input> element that has a required attribute.

For example:

Example of two input elements the first including the required attribute.

Only the first input matches the selector because it includes the required attribute.

You can also target a specific attribute value.

Example of input type email.

Now CSS selects only inputs where type is email.

You Can Match only a part of an attribute value

CSS provides several operators for making more precise matches. The $= operator checks the end of the href value, meaning that a link like <a href="guide.pdf"> would be a match.

For example, this selects links that point to PDF files:

Example of the $= operator checking the end of the href value.

You can also use the ^= operator to check the start of the attribute value.

You can use it to target external links that start with https://:

Example of the ^= operator checking the start of the href value

Here, ^= means “starts with.”

Or using the *=operator to check if the attribute contains a specific piece of text anywhere in its value.

Example of the *=operator checking if href contains the word programmer in its value.

This matches all links where href contains "programmer":

Example of three different links containing the word programmer.

All three match because "programmer" is included somewhere inside the href value.

When should you use attribute selectors?

Attribute selectors are useful for forms, links, buttons and elements in general where an attribute describe the element. They keep your HTML code cleaner because you don’t have to create a new class for every small styling rule.

Although my blog doesn’t support comments, feel free to reply via email or X.