CSS Attribute Selectors

CSS Attribute Selectors allow you to apply styles to elements based on the presence or value of their attributes. They provide a way to target elements more precisely based on their attributes and values.

Types of Attribute Selectors

There are several types of attribute selectors that you can use:

1. Presence Selector

The presence selector applies styles to elements that have a specific attribute, regardless of its value.


/* Presence Selector */
a[href] {
    color: blue;
}

        

In this example, all `` elements with an `href` attribute will be styled with a blue color.

2. Exact Match Selector

The exact match selector applies styles to elements with an attribute that exactly matches a specified value.


/* Exact Match Selector */
input[type="text"] {
    border: 2px solid green;
}

        

Here, only `` elements with the `type` attribute exactly equal to "text" will have a green border.

3. Contains Word Selector

The contains word selector applies styles to elements where the attribute's value contains a specific word.


/* Contains Word Selector */
a[title~="external"] {
    font-weight: bold;
}

        

This selector targets `` elements where the `title` attribute contains the word "external" and makes the text bold.

4. Starts With Selector

The starts with selector applies styles to elements whose attribute value begins with a specified value.


/* Starts With Selector */
input[name^="user"] {
    background-color: #f0f0f0;
}

        

This example targets `` elements where the `name` attribute starts with "user" and sets the background color to light gray.

5. Ends With Selector

The ends with selector applies styles to elements whose attribute value ends with a specified value.


/* Ends With Selector */
a[href$=".pdf"] {
    color: red;
}

        

This selector targets `` elements whose `href` attribute ends with ".pdf" and sets the color to red.

6. Contains Selector

The contains selector applies styles to elements where the attribute's value contains a specified substring.


/* Contains Selector */
a[href*="example"] {
    text-decoration: underline;
}

        

Here, `` elements whose `href` attribute contains the substring "example" will have underlined text.