user
In CSS how to select an element by attribute?
alphonsio

In CSS, you can select an element based on its attribute using attribute selectors. The syntax for this involves using square brackets around the attribute name and optionally the attribute value. Here are a few different types of attribute selectors:

  1. Attribute Presence Selector: Selects elements that have the specified attribute, regardless of its value.

    [attribute] {
       /* styles */
    }
  2. Attribute Value Selector: Selects elements with an attribute set to a specific value.

    [attribute="value"] {
       /* styles */
    }
  3. Attribute Substring Selector: Selects elements with an attribute containing a specified word within its value.

    [attribute*="value"] {
       /* styles */
    }
  4. Attribute Starts With Selector: Selects elements with an attribute value beginning exactly with a specified string.

    [attribute^="value"] {
       /* styles */
    }
  5. Attribute Ends With Selector: Selects elements with an attribute value ending exactly with a specified string.

    [attribute$="value"] {
       /* styles */
    }
  6. Attribute Hyphenated Selector: Select elements with an attribute name of attribute whose value can be exactly value or can begin with value immediately followed by a hyphen, - (U+002D). It is often used for language subcode matches.

    [attribute|="value"] {
       /* styles */
    }

For example, if you want to select all input elements where the type attribute is 'text', you can use:

input[type="text"] {
    /* styles */
}

These attribute selectors can be very useful for applying specific styles to elements based on their attributes, offering you a robust method of selecting elements in your CSS.

Here is a live example: