CSS Attribute Selectors

CSS Attribute Selectors allow you to select HTML elements based on their attributes or attribute values. They are useful when you want to style specific elements without adding extra classes or IDs.

For example, you can use attribute selectors to style links, form inputs, and buttons based on their attributes.

CSS Attribute Selector Syntax

The basic syntax selects elements that contain a particular attribute.

[attribute] {
    property: value;
}

To select elements with a specific attribute value, use:

[attribute="value"] {
    property: value;
}

Selecting Elements by Attribute

You can select all elements that contain a particular attribute, regardless of its value.

<style>
    [title] {
        color: blue;
    }
</style>

<p title="information">This paragraph has a title attribute.</p>
<p>This paragraph does not have a title attribute.</p>

The first paragraph appears blue because it contains the title attribute.

Selecting Elements by Attribute Value

You can target elements whose attributes have an exact value.

<style>
    input[type="text"] {
        border: 2px solid blue;
    }

    input[type="password"] {
        border: 2px solid green;
    }
</style>

<input type="text" placeholder="Enter your name">
<input type="password" placeholder="Enter your password">

The text input receives a blue border, while the password input receives a green border.

Learn more about input elements in our HTML Attributes and HTML Forms tutorials.

Common CSS Attribute Selectors

SelectorDescription
[title]Selects elements with a title attribute
[type="text"]Selects elements with an exact attribute value
[class~="note"]Selects elements whose space-separated class list contains note
[href^="https"]Selects elements whose href starts with https
[href$=".pdf"]Selects elements whose href ends with .pdf
[href*="example"]Selects elements whose href contains example

Using Attribute Selectors for Links

Attribute selectors can help style links based on their destinations.

<style>
    a[href$=".pdf"] {
        color: red;
        font-weight: bold;
    }
</style>

<a href="/files/guide.pdf">Download the PDF guide</a>
<a href="/tutorials/css/">Read CSS tutorials</a>

The first link appears red and bold because its href ends with .pdf.

Why Are CSS Attribute Selectors Useful?

Attribute selectors let you target elements based on existing HTML attributes. They are especially useful for styling form controls, identifying particular links, and applying styles without adding extra classes.

You can also explore our CSS Class Selector and CSS ID Selector tutorials to learn other ways of selecting HTML elements.