CSS Attribute Selector
The CSS attribute selector is used to style elements based on the presence, value, or partial value of their attributes. This allows for more precise targeting of elements without the need for additional classes or IDs.
The syntax for an attribute selector is:
selector[attribute] {
property: value;
}
Variations of the attribute selector include:
selector[attribute="value"] {
/* Exact match */
}
selector[attribute^="value"] {
/* Starts with */
}
selector[attribute$="value"] {
/* Ends with */
}
selector[attribute*="value"] {
/* Contains */
}
Where:
Parameter | Description |
---|---|
selector | The HTML element being styled. |
attribute | The attribute to target (e.g., type , href ). |
value | The value or partial value to match. |
Examples
Styling Elements with a Specific Attribute
In this example, we style all elements that have a data-highlight
attribute, setting their background color to yellow.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
[data-highlight] {
background-color: yellow;
}
</style>
</head>
<body>
<div data-highlight>This div is highlighted.</div>
<p>This paragraph is not highlighted.</p>
</body>
</html>
Styling Elements with an Exact Attribute Value
Here, we style all <input>
elements where the type
attribute is exactly "text"
, setting their border to 2px solid blue.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
input[type="text"] {
border: 2px solid blue;
}
</style>
</head>
<body>
<input type="text" placeholder="Text input">
<input type="password" placeholder="Password input">
</body>
</html>
Styling Elements with an Attribute Value That Starts With
In this example, we style all <a>
elements where the href
attribute starts with "https"
, changing their text color to green.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
a[href^="https"] {
color: green;
}
</style>
</head>
<body>
<a href="https://example.com">Secure Link</a>
<a href="http://example.com">Insecure Link</a>
</body>
</html>
Styling Elements with an Attribute Value That Contains
Here, we style all <p>
elements where the class
attribute contains the word "note"
, setting their font style to italic.
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
p[class*="note"] {
font-style: italic;
}
</style>
</head>
<body>
<p class="important-note">This is an important note.</p>
<p class="general-text">This is general text.</p>
</body>
</html>