HTML elements with particular properties or attribute values can be styled.
CSS [attribute] Selector
You can choose elements with a certain property by using the [attribute] selector.
The example that follows picks every <a> element that has a target attribute:
Example
a[target] {
background-color: yellow;
}
CSS [attribute="value"] Selector
The items with the given attribute and value can be chosen using the [attribute=”value”] selector.
The example that follows picks every <a> element that has the target=”_blank” attribute:
Example
a[target="_blank"] {
background-color: yellow;
}
CSS [attribute~="value"] Selector
Elements with an attribute value containing a given word can be chosen using the [attribute~=”value”] selector.
The example that follows picks out every element with a title property that has a list of words separated by spaces, among which is “flower”:
Example
[title~="flower"] {
border: 5px solid yellow;
}
The example above will match elements with title=”flower”, title=”summer flower”, and title=”flower new”, but not title=”my-flower” or title=”flowers”.
CSS [attribute|="value"] Selector
Elements containing the specified property, whose value can either be the supplied value exactly or the specified value followed by a hyphen (-), can be selected with the [attribute|=”value”] selector.
Note: The value must consist of a single word, such as class=”top,” or a word followed by a hyphen (-), such as class=”top-text.”
Example
[class|="top"] {
background: yellow;
}
CSS [attribute^="value"] Selector
To choose items with the specified attribute whose value begins with the supplied value, use the [attribute^=”value”] selector.
The example that follows picks every element whose class attribute value begins with “top”:
Note: A complete word need not be the value!
Example
[class^="top"] {
background: yellow;
}
CSS [attribute$="value"] Selector
Elements whose attribute value ends with a certain value can be chosen using the [attribute$=”value”] selector.
The example that follows picks every element whose class attribute value ends in “test”:
Note: A complete word need not be the value!
Example
[class$="test"] {
background: yellow;
}
CSS [attribute*="value"] Selector
Elements whose attribute value contains a specific value can be chosen using the [attribute*=”value”]selector.
The example that follows picks every element whose class attribute value contains “te”:
Note: A complete word need not be the value!
Example
[class*="te"] {
background: yellow;
}
Styling Forms
When it comes to decorating forms without class or ID, attribute selectors can be helpful: