Master CSS From Scratch

Clear, interactive, and structured CSS lessons designed for beginners.

Attribute Selector

An attribute selector is used to select HTML elements based on their attributes and attribute values.

What is an Attribute Selector?

CSS attribute selectors allow you to target HTML elements that contain a specific attribute.

Attribute selectors are written using square brackets [].

Attribute Selector Flow

HTML Element
<input type="text">
↓
Attribute Selector
[type="text"]
↓
Applied CSS Style

Basic Syntax

[attribute] {
    property: value;
}

The selector inside square brackets targets elements that contain the specified attribute.

Example 1: Select Elements by Attribute

[type] {
    border: 2px solid blue;
}

Output

Example 2: Select a Specific Attribute Value

input[type="text"] {
    background-color: lightblue;
}

Output

Example 3: Link Attribute Selector

a[target="_blank"] {
    color: red;
}

Output

Common Attribute Selectors

Selector Meaning
[type] Selects elements having a type attribute.
[type="text"] Selects elements with type equal to text.
[target="_blank"] Selects links having target="_blank".
[class] Selects elements having a class attribute.

Important Points

  • Attribute selectors use square brackets [].
  • They can select elements based on the presence of an attribute.
  • They can also select elements based on a specific attribute value.
  • Attribute selectors are useful for styling form controls and links.

Summary

Attribute selectors allow CSS to target HTML elements using their attributes or attribute values. They are written using square brackets and are useful for selecting specific types of elements.