View video tutorial
CSS Attribute Selectors
CSS
CSS attribute selectors are used to select HTML elements based on the presence or value of their attributes and then apply CSS styles to the selected HTML elements.
CSS attribute selectors
➔ The selection is based on element attributes or attribute values.
➔ These selectors are always enclosed in square brackets [ ].
CSS Common Attribute Selectors.
There are several ways to match attribute values using css attribute selectors.
[attr]{}Styles elements with specific attributes, regardless of their value.[attr="value"]{}Styles elements with specified attributes whose values match exactly.[attr~="value"]{}Styles elements whose attribute values are a list of whitespace-separated words and one of them matches the value exactly. Ex. [class~="ab"] matches elements with class="ab", class="ab cd", but not class="abcd".[attr|="value"]{}Style elements whose attribute values start with exactly "value" or "value" followed by a hyphen (-). Ex: [lang|="en"] matches lang="en" and lang="en-US"[attr^="value"]{}Styles elements whose attribute values start with exactly "value". Ex: a[href^="https://"] matches all href attribute value begins with "https://".[attr$="value"]{}Styles the elements whose attribute value ends with the specified "value". Ex: img[src$=".png"] matches all src attribute value ends with ".png".[attr*="value"]{}Styles elements whose attribute value contains the specified "value" anywhere in the string. Ex: [src*="css"] matches src="/css/images/logo.png"
Syntax
selector[attr]{CSS properties;}
selector[attr='value']{CSS properties;}
Syntax description.
| Value | Description |
|---|---|
| selector | Specifies any CSS selector. Such as div, a, input, etc. |
| attr | Specifies any CSS attribute name. For example type, target etc. |
| value | Specifies attribute value. For example type='text', target='_blank' etc. |
| CSS properties | Specifies any CSS property enclosed in {}, such as {color: #FF0000;background-color: blue;} |
input[type="text"] {
color: #067080;
background-color:#e7e7e7 1;
}
Example
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta charset="utf-8" />
<title>CSS attribute selector example</title>
<style>
a[target] {
color: red;
}
input[type='text'] {
background-color: #10f0f0;
}
a:hover {
color: green;
}
</style>
</head>
<body>
<h3>CSS attribute selector example</h3>
<input type="text" placeholder="Enter name">
<p><a href="/css/" target="_blank">visit CSS Chapter.</a></p>
<p><b>Note:</b> attribute selectors are used to select HTML elements based on the presence or value of their
attributes and then apply CSS styles to the selected HTML elements.</p>
</body>
</html>
Copy the code and click on the "Try it Now" button to see how it works.