Sobes.tech
Intern

What attribute selectors exist in CSS?

sobes.tech AI

Answer from AI

Attribute selectors in CSS allow selecting elements based on their attributes and attribute values. Main types of attribute selectors:

  1. [attribute] - Selects all elements with the specified attribute, regardless of its value.

    /* Selects all elements with the "title" attribute */
    [title] {
      color: blue;
    }
    
  2. [attribute="value"] - Selects all elements where the specified attribute has exactly the given value.

    /* Selects all links where the "href" attribute equals "https://example.com" */
    a[href="https://example.com"] {
      text-decoration: none;
    }
    
  3. [attribute~="value"] - Selects all elements where the specified attribute contains the given value as a separate word in a space-separated list.

    /* Selects elements with the class "highlight" */
    [class~="highlight"] {
      background-color: yellow;
    }
    
  4. [attribute|="value"] - Selects all elements where the specified attribute is exactly equal to the value or starts with the value followed by a hyphen (-). Mainly used for language attributes (lang) or prefixes.

    /* Selects elements with lang="en" or lang="en-US" */
    [lang|="en"] {
      font-style: italic;
    }
    
  5. [attribute^="value"] - Selects all elements where the specified attribute starts with the given value.

    /* Selects all links starting with "https://" */
    a[href^="https://"] {
      color: green;
    }
    
  6. [attribute$="value"] - Selects all elements where the specified attribute ends with the given value.

    /* Selects all links ending with ".pdf" */
    a[href$=".pdf"] {
      font-weight: bold;
    }
    
  7. [attribute*="value"] - Selects all elements where the specified attribute contains the given value anywhere in the string.

    /* Selects all links containing "example" in their address */
    a[href*="example"] {
      border: 1px solid black;
    }
    

These selectors can be combined with other types of selectors (by tag, class, ID, etc.) to create more specific rules.