Attribute selectors are used to target HTML elements based on their attributes and attribute values.
They help developers style elements dynamically without adding extra classes.
Attribute selectors are commonly used in:
- Forms
- Links
- Dynamic UI systems
- Reusable components
- Custom data attributes
Why Attribute Selectors Are Important
Without attribute selectors, developers often need additional classes or JavaScript.
These selectors create:
- Cleaner HTML
- Reusable CSS
- Flexible UI logic
- Better maintainability
Common Attribute Selectors
|
Selector
|
Purpose
|
|
[type]
|
Elements containing type attribute
|
|
[type="text"]
|
Exact attribute value
|
|
[href^="https"]
|
Value starts with text
|
|
[class*="box"]
|
Value contains text
|
|
[data-id]
|
Custom data attribute selector
|
1. [type]
Selects elements that contain the:
[code theme="dark"]
type
[/code]
attribute.
Example
[code theme="dark"]
[type]{
border:2px solid blue;
}
[/code]
HTML Structure
[code theme="dark"]
[/code]
Live Demo
2. [type="text"]
Selects elements with an exact attribute value.
[code theme="dark"]
[type="text"]{
background:#dbeafe;
}
[/code]
HTML Structure
[code theme="dark"]
[/code]
Live Demo
3. [href^="https"]
The:
[code theme="dark"]
^=
[/code]
operator checks if the value starts with specific text.
[code theme="dark"]
[href^="https"]{
color:green;
}
[/code]
Targets secure HTTPS links.
HTML Structure
[code theme="dark"]
Secure Link
Normal Link
[/code]
Live Demo
4. [class*="box"]
The:
[code theme="dark"]
*=
[/code]
operator checks if the value contains specific text.
[code theme="dark"]
[class*="box"]{
padding:20px;
}
[/code]
HTML Structure
[code theme="dark"]
[/code]
Live Demo
5. [data-id]
Selects elements containing custom:
[code theme="dark"]
data-
[/code]
attributes.
[code theme="dark"]
[data-id]{
border-left:4px solid blue;
}
[/code]
HTML Structure
[code theme="dark"]
Product Card
[/code]
Live Demo
Product Card
Common Attribute Operators
|
Operator
|
Meaning
|
|
=
|
Exact match
|
|
^=
|
Starts with
|
|
$=
|
Ends with
|
|
*=
|
Contains text
|
Advantages of Attribute Selectors
- Cleaner HTML structure
- No extra classes needed
- Dynamic UI targeting
- Powerful reusable CSS
- Useful for forms and components
Disadvantages
- Complex selectors may reduce readability
- Large DOM usage may affect performance slightly
- Overuse can make CSS harder to debug
Cross Browser Compatibility
CSS attribute selectors are fully supported across all modern browsers.