CSS attribute selector selects the HTML elements that has a specific attribute or attribute with a specified value. This is the simplest form of an attribute selector that applies the style rules to an element if a given attribute exists. For example, we can style all the elements that have a title
attribute by using the following style rules:
[title] { color: red; }
CSS Attribute Selector [attribute=”value”]
You can use the =
operator to make an attribute selector matches any element whose attribute value is exactly equal to the given value
input[type="submit"] { border: 2px blue; }
The selector in the above example matches all <input>
element that has a type
attribute with a value equal to submit
.
CSS Attribute Selector [attribute~=”value”]
You can use the ~=
operator to make an attribute selector matches any element whose attribute value is a list of space-separated values (like class="alert warning"
) , one of which is exactly equal to the specified value:
[class~="warning"] { color: #fff; background: red; }
This selector matches any HTML element with a class
attribute that contains space-separated values, one of which is warning
. For example, it matches the elements having the class values warning
, alert warning
etc.
CSS Attribute Selector [attribute|=”value”]
The [attribute|="value"]
selector is used to select elements with the specified attribute starting with the specified value.
The following example selects all elements with a class attribute value that begins with “top”
[class|="top"] { background: red; }
CSS Attribute Selector [attribute^=”value”]
You can use the ^=
operator to make an attribute selector matches any element whose attribute value starts with a specified value. It does not have to be a whole word.
[class^="top"] { background: green; }
CSS Attribute selector [attribute$=”value”]
Similarly, you can use the $=
operator to select all elements whose attribute value ends with a specified value. It does not have to be a whole word.
[class$="test"] { background: pink; }
Comments are closed.