CodeBlanks Logo Icon CodeBlanks

Attribute selectors

CSS course · Beginner · Lesson 11/82

Learn [attr] and [attr=value] selectors.

Attribute selector

An attribute selector picks elements by an HTML attribute. Its simplest form writes just the attribute name inside square brackets, like [href]. This selector matches any element carrying the href attribute.

Attribute selectors are ideal for targeting specific markers like links, form fields, and data attributes. They are sharper than a type selector and less committal than a class.

Match by value

To also match the attribute value, use the [attr=value] form. input[type="checkbox"] selects only input elements with type="checkbox".

The value goes in quotes; single or double quotes both work. This precise match makes targeting form controls and data-attributed elements much easier. A type selector grabs every input, while an attribute selector picks only the subset you want.

Exercise Add two attribute selectors

Write two separate style blocks. First an input[type="email"] selector with border-color: teal. Second an a[href] selector with color: navy.

Show example solution
/* add attribute selectors */
input[type="email"] {
  border-color: teal;
}
a[href] {
  color: navy;
}

Test yourself

  1. Which selector matches only email inputs?

    • input
    • input[type="email"]
    • input.email
    • #email
    Show answer

    input[type="email"] — Correct. input[type="email"] selects only input elements with type="email".

  2. Write the checkbox selector

    ____ {
      accent-color: teal;
    }
    Show answer
    [type="checkbox"] {
      accent-color: teal;
    }
  3. Match each attribute selector to its meaning

    [href]
    All elements carrying href
    [type="email"]
    Those whose type is email
    a[href]
    All a tags that are links
    [disabled]
    Elements that are disabled

All lessons in Beginner