CSS Attribute Selectors

CSS Attribute Selectors


CSS Attribute Selector 
Attribute selectors can be used with various types of operators that change the selection criteria accordingly. 
They select an element using the presence of a given attribute or attribute value.
NOTE - 
1. The attribute value can be surrounded by either single quotes or double quotes. 
No quotes at all may also work, but it's not valid according to the CSS standard and is discouraged. 
2. There is no single, integrated CSS4 specification, because it is split into separate modules. However, there are "level 4" modules.
Now we will see Examples/Details -
Example - 
[attribute]
Selects elements with the given attribute.
HTML - 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>CSS Selectors</title>
</head>
<body>
    <div data-color="red">This will be red</div>
    <div data-color="red">This will be red</div>
    <div data-background="red">This will NOT be red</div>
</body>
</html>
CSS - 
div[data-color] {
  color: red;
}
Output - 
Example 2 - 
[attribute="value"] 
Selects elements with the given attribute and value.
div[data-color="red"] {
color: red;
}
<div data-color="red">This will be red</div>
<div data-color="green">This will NOT be red</div>
<div data-color="blue">This will NOT be red</div>
Output - 
Example 3 -
[attribute*="value"]
Selects elements with the given attribute and value where the given attribute contains the given value anywhere (as
a substring).
[class*="foo"] {
color: red;
}
<div class="foo-123">This will be red</div>
<div class="foo123">This will be red</div>
<div class="bar123foo">This will be red</div>
<div class="barfooo123">This will be red</div>
<div class="barfo0">This will NOT be red</div>
Output -
Example -
[attribute~="value"]
Selects elements with the given attribute and value where the given value appears in a whitespace-separated list.
[class~="color-red"] {
color: red;
}
<div class="color-red foo-bar the-div">This will be red</div>
<div class="color-blue foo-bar the-div">This will NOT be red</div>
Output - 
Example -
[attribute^="value"]
Selects elements with the given attribute and value where the given attribute begins with the value.
[class^="foo-"] {
color: red;
}
<div class="foo-123">This will be red</div>
<div class="foo-234">This will be red</div>
<div class="bar-123">This will NOT be red</div>
Output - 
Example  - 
[attribute$="value"]
Selects elements with the given attribute and value where the given attribute ends with the given value.
[class$="file"] {
color: red;
}
<div class="foobar-file">This will be red</div>
<div class="foobar-file">This will be red</div>
<div class="foobar-input">This will NOT be red</div>

 
Output -