Skip to main content

CSS Attribute Selectors: Target Elements with Precision

CSS [Attribute] Selectors

CSS Attribute Selectors allow you to select HTML elements based on the presence or value of their attributes.

Here are a few examples of how you can use CSS Attribute Selectors:

The [attribute] Selector

This selector targets elements that have the specified attribute, regardless of its value.

As an example:

Editor

Loading...

The [attribute=value] Selector

This selector targets elements that have the specified attribute with a specific value.

As an example:

Editor

Loading...

In this example:

  • The CSS selector a[href="#top"] targets all links with an href value of "#top".
  • In this case, it only matches the first link in the list.
  • The text-decoration:none; property removes the underline from the link's text.

The [attribute^=value] Selector

This selector targets elements that have the specified attribute with a value that starts with the specified value.

As an example:

Editor

Loading...

In this example:

  • The CSS selector [class^="example"] targets all elements that have a "class" attribute starting with "example".
  • This includes the first three elements in the HTML code (the div, p, and span), but not the fourth one (the p with multiple classes).
  • The font-weight: bold; property sets the font weight of the text inside those elements to bold.

The [attribute$=value] Selector

This selector targets elements that have the specified attribute with a value that ends with the specified value.

As an example:

Editor

Loading...

In this example:

  • The CSS selector [href$=".pdf"] targets all elements with an "href" attribute that ends with ".pdf".
  • This includes the first two links in the HTML code.
  • The color: red; property sets the color of the text inside those links to red.

The [attribute*=value] Selector

This selector targets elements that have the specified attribute with a value that contains the specified value.

As an example:

Editor

Loading...

In this example:

  • The CSS selector [src*="logo"] targets all elements with a "src" attribute that contains the word "logo".
  • This includes the first two images in the HTML code.
  • The width: 300px; property sets the width of those images to 300 pixels.
info

The selector also targets the iframe and audio elements, which have "src" attributes that contain the word "logo".