Using CSS’s Attribute Selectors, Part 2

We’ve already learned the basics of how to select HTML elements in your CSS by their attributes, values, or both, but it turns out there are also other options available to us when selecting attributes and values. Check them out below.

[attribute~=”value”]

This selector is used to find HTML elements with an attribute value that contains a word. So if you want to to select all elements with the word orange in their title, you would do this:

Join us in our newest publication:
[title~="orange"]

Even if a title was “orange-2”, that element would still be selected.

[attribute^=”value”]

This one will select any HTML element where the selected attribute’s value begins with the word in the “value” slot — it doesn’t have to be the whole word! But it has to begin with it. So in the example below:

[class^="small"]

An HTML element with the class “small-text” would be selected, as would one with the class “smallest” but not one with the class “text-small”.

[attribute|=”value”]

This is selector is very similar to the one above. It selects all HTML elements where the selected attribute’s value begins with the word in the value slot, HOWEVER, it has to be a whole word, it can’t just be part of the word. So using the same example above, an HTML element with the class “small-text” would be selected, but not “smallest” (and still not “text-small”!)

[attribute$=”value”]

This is the opposite of the selectors above. This one is used to select all HTML elements where the selected attribute’s value ENDS with the word in the value slot — and it doesn’t have to be the whole word.

[class$="small"]

So in the example above, an element with the class of “text-small” would be selected, and “sosmall” but not “small-text”.

[attribute*=”value”]

Last but not least, this selector will select any element where the selected attribute’s value contains the characters in the value slot — it doesn’t have to be a whole word OR at the end or the beginning.

[class*="small"]

So in this case, elements with classes “smallest”, “small-text”, “text-small”, and “sosmall” would all be selected.

Share and Enjoy !

0Shares
0 0