Attribute Selectors in CSS

Learn how to target elements based on their HTML attributes and attribute values.

Attribute selectors let you target elements based on their HTML attributes — whether an attribute exists, or what its value is.

Basic Attribute Selector

/* Target all elements with a "title" attribute */
[title] {
    cursor: help;
    border-bottom: 1px dotted;
}

/* Target all inputs with a "required" attribute */
input[required] {
    border-color: red;
}

Exact Value Match

/* Target inputs of type "text" */
input[type="text"] {
    padding: 0.5rem;
    border: 1px solid #ccc;
}

/* Target links that open in a new tab */
a[target="_blank"] {
    color: orange;
}

Partial Value Matches

/* Starts with — href begins with "https" */
a[href^="https"] { color: green; }

/* Ends with — href ends with ".pdf" */
a[href$=".pdf"] { color: red; }

/* Contains — href contains "example" */
a[href*="example"] { font-weight: bold; }

Practical Examples

/* Style all external links differently */
a[href^="http"] {
    padding-right: 1rem;
    background: url('external-icon.svg') no-repeat right center;
}

/* Style disabled inputs */
input[disabled] {
    opacity: 0.5;
    cursor: not-allowed;
}