CSS Attribute Selectors
CSS Attribute Selectors are used to target HTML elements with a specific attribute or attribute value, for example, target all elements with a 'class' attribute, anchor tags where the 'target' attribute is set to '_blank' or input elements with a 'type' of 'text'.
The following Attribute Selector targets all elements with a 'class' attribute and sets the text colour to red.
[class] { color: red; }
It is also possible to target, for example, just paragraphs with a 'class' attribute, or indeed any other HTML element.
p[class] { color: red; }
As well as being able to target elements with a specific attribute, it is also possible to target elements with a specific attribute and attribute value, for example, an anchor tag where the 'target' is set to '_blank' meaning that the link will open up in another tab or window. This example sets the link text to uppercase.
a[target="_blank"] { text-transform: uppercase; }
The following example targets text input elements only, select or drop-down boxes, text areas and other input elements will not be affected. Here the text colour is set to blue for text input elements.
input[type="text"] { color: blue; }
As well as being able to target elements that have a particular attribute, which equals a particular value, it is possible to target elements where an attribute value contains, starts with, begins with or ends with a particular value.
The CSS rule below targets HTML elements with a 'title' attribute that contains the text 'CSS' and sets the text colour to red. Note that it won't pick up elements where the value is part of a larger value, it needs to be separated in some way, such as with a hyphen or space.
[title~="CSS"] { color: red; }
If it is required to match the letters 'CS' in a larger value, such as 'CSS', the '*' symbol can be used.
[title*="CS"] { color: red; }
To target attributes where the value starts with a particular value, the '|' symbol has to be used. Here the CSS rule targets classes that start with the word 'top'.
[class|="top"] { color: red; }
Note that this CSS rule would target a class named, for example, 'top-paragraph', but not 'topparagraph'. The value has to be separated somehow, either with a hyphen or underscore, in the case of a class name, or a space with the title attribute.
The above example could be changed to target classes that begin with 'top', where it is part of a larger value, such as 'topparagraph', using the '^' symbol.
[class^="top"] { color: red; }
Similarly, it is possible to target elements where the value of an attribute ends with a specific value using the '$' symbol. The below example would target classes such as 'paragraphtop'.
[class$="top"] { color: red; }