Definition and Usage
The [attribute^="value"] selector selects all elements that have a specified attribute whose value starts with value.
For example, [href^="#"] selects all elements with a href attribute value starting with #, such as href="#subject-1" and href="#contact".
The [attribute^="value"] selector matches elements that have a attribute whose value starts with the prefix value.
It also does not match any elements if the value of the attribute is an empty string ("").
The following basic example makes this easier to understand.
Basic Example
/* Selects all elements with a href
attribute value starting with "#". */
[href^="#"] {
background-color: darkblue;
color: white;
}
[href^="#"]::after {
content: " 👇";
}
<p>See the following links.</p>
<ul>
<li><a href="#subject-1">Subject 1</a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="https://example.com/">Example Domain</a></li>
</ul>
Syntax
The following two syntaxes are equivalent.
[attribute^="value"][attribute^='value']
[href^="#"] {
background-color: darkblue;
color: white;
}
/* The following is also equivalent. */
[href^='#'] {
background-color: darkblue;
color: white;
}
Notes
The [attribute^="value"] selector selects elements whose attribute value starts with a specific value,
In contrast, the [attribute$="value"] selector selects elements whose attribute value ends with a specific value.
/* Selects all elements with an href
attribute value ending with ".html". */
[href$=".html"] {
background-color: darkblue;
color: white;
}
[href$=".html"]::after {
content: " 📗";
}
<p>See the following links.</p>
<ul>
<li><a href="home.html">Home</a></li>
<li><a href="contact.html">Contact</a></li>
<li><a href="https://example.com/">Example Domain</a></li>
</ul>
Browser Compatibility
| Selector |
Desktop Chrome
|
Desktop Edge
|
Desktop Firefox
|
Safari
|
|---|---|---|---|---|
[attribute^="value"]
|
1 | 12 | 1 | 3 |
Specifications
| Specification | |
|---|---|
[attribute^="value"]
|
Selectors Level 4 #attribute-selectors |
References
See Also
- CSS [attribute] Selector – Select Elements by Attribute Name
- CSS [attribute="value"] Selector – Select Elements by Attribute Name and Value
- CSS [attribute*="value"] Selector - Select Elements Whose Attribute Value Contains a Substring
- CSS [attribute~="value"] Selector – Select Elements Whose Attribute Value Contains a Word
- CSS [attribute$="value"] Selector – Select Elements Whose Attribute Value Ends With a Specific Value
- CSS * Selector – Selects All Elements
- CSS Element Selector – Select by Element Name
- HTML Attribute Reference