Skip to main content

Attribute Selectors in CSS (Live Playground)

Attribute selectors in CSS allow you to target and style HTML elements based on their attributes and attribute values. This provides an additional level of specificity and control when styling elements on your web page. In this tutorial, you will learn how to use attribute selectors effectively, along with sample code and simple explanations.

Basic attribute selectors

To target an HTML element with a specific attribute, use the attribute selector syntax: [attribute]. The styles within the declaration block will be applied to all elements with the specified attribute.

Example:

CSS
/* Target all elements with a "data-active" attribute */
[data-active] {
border: 2px solid green;
}
HTML
<p data-active>This paragraph has a green border.</p>

In this example, the attribute selector [data-active] targets elements with the "data-active" attribute and applies the specified border style.

Live Playground, Try it Yourself

Attribute value selectors

You can also target elements with a specific attribute value by using the attribute value selector syntax: [attribute="value"].

Example:

CSS
/* Target all input elements with a "type" attribute value of "text" */
input[type='text'] {
background-color: lightblue;
}
HTML
<input type="text" value="This input has a light blue background." />

In this example, the attribute value selector input[type="text"] targets input elements with a "type" attribute value of "text" and applies the specified background-color style.

Live Playground, Try it Yourself

Other attribute selector variations

CSS also provides other attribute selector variations for more complex targeting:

  • [attribute^="value"]: Targets elements with an attribute value beginning with the specified value
  • [attribute$="value"]: Targets elements with an attribute value ending with the specified value
  • [attribute*="value"]: Targets elements with an attribute value containing the specified value

Example:

CSS
/* Target all elements with a "data-category" attribute value starting with "animal" */
[data-category^='animal'] {
font-weight: bold;
}

/* Target all elements with a "data-category" attribute value ending with "plant" */
[data-category$='plant'] {
font-style: italic;
}

/* Target all elements with a "data-category" attribute value containing "vehicle" */
[data-category*='vehicle'] {
text-decoration: underline;
}
HTML
<p data-category="animal-mammal">This paragraph has bold text.</p>
<p data-category="flowering-plant">This paragraph has italic text.</p>
<p data-category="land-vehicle">This paragraph has underlined text.</p>
Live Playground, Try it Yourself

Conclusion

In this tutorial, you learned how to use attribute selectors in CSS to target and style HTML elements based on their attributes and attribute values. With this knowledge, you can achieve more precise and flexible control over the styling of elements on your web page.