I know this is something I should have learnt a long time ago but I put it off for years. Here is how to use regular expressions in css selectors. This allows you to target elements attribute values that either begin, end, or contain somewhere your desired text string.
The ^
1 |
[class^="mo"] {background:yellow;} /*class attribute begins with mo*/ |
The example above will select all elements containing a class which begins with ‘mo’. Examples of this would be elements with classes such as moon, motech, modern.
The $
1 |
[class$="mo"] {color:red;} /*class attribute ends with mo*/ |
The example above will select all elements containing a class which end with ‘mo’. Examples of this would be elements with classes such ammo, emo, alamo.
The *
1 |
[class*="mo"] {color:red;} /*class attribute contains mo anywhere within it*/ |
The example above will select all elements containing a class which contains ‘mo’ somewhere in it. Examples of this would be elements with classes such slowmotion, emotion, and locomotive.
You can target other attributes
You can select elements based on any attribute – not just class. You might consider selecting link elements based on the href value. Often times this is a useful technique I use if I want all phone number links to be styled uniformly in a way that sticks out as a call to action. See the code below:
1 |
a[href^="tel"] { text-decoration:underline;color:green; } |
This will make it so that all links where the href value begins with ‘tel’ (which is the standard protocol for phone number links) will be underlined and have the color green. Another idea to consider is that you might want to have all links to a given webpage by styled a certain way – here’s how you would do that:
1 |
a[href*="cnn.com"] { font-weight:bold; font-size:200%; } |
And Voila – now all your links to sites on cnn.com will be bolded and extra large.
That’s all!
Well, you now know how to use regular expressions in css! Give yourself a pat on the back, you’ve earned it.