Attribute selectors in CSS

The most basic CSS selectors that we use are id, class, and tag-name. But sometimes based on requirements we may need to select elements by some specific attributes.

div[tabindex] {
    border: 1px solid red;
}

This will select all div elements with attribute tabindex and set the border.

Now to select all the elements that have the attribute tabindex, we would do this:

*[tabindex] {
   border: 1px solid red;
}

/* Or */
[tabindex] {
    border: 1px solid red;
}

Attribute with a value

input[type="text"] {
   width: 100px;
   height: 40px;
}

This will select all the input elements with the attribute type=”text” and set the width and height.

We have different types of syntax available to use when we provide an attribute with a value. We can select the right syntax based on our attribute value matching preference. Let’s check them one by one.

[attribute~=”value”]

img[alt~="tooltip"] {
   width: 30px;
   height: 30px;
}

This selector selects all the img elements with alt attribute values containing the word “tooltip”.

[attribute|=”value”]

img[alt|="tooltip"] {
   width: 30px;
   height: 30px;
}

This selector selects all the img elements with alt attribute values starting with the word “tooltip”.

[attribute^=”value”]

img[alt^="tool"] {
   width: 30px;
   height: 30px;
}

This selector selects all the img elements with alt attribute values starting with the letter “tool”.

[attribute$=”value”]

img[src$=".png"] {
   width: 30px;
   height: 30px;
}

This selector selects all the img elements with src attribute values ending with the letter “.png”.

[attribute*=”value”]

img[alt*="icon"] {
   width: 30px;
   height: 30px;
}

This selector selects all the img elements with alt attribute values containing the letter “icon”.

See Next

The CSS :is() and :where() pseudo-classes to write shorter compound selectors

Leave a Reply

Your email address will not be published. Required fields are marked *