You are here: Blog » Tutorials » How To Use Regular Expressions In CSS

How To Use Regular Expressions In CSS

regex-regular-expression

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 ^

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 $

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 *

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:

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:

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.

 

This entry was posted in Tutorials and tagged , , by .

Author: justin saad

Justin Saad is first and foremost a husband and a father of four. He is also a web developer and designer who has been making websites for over fifteen years. His company is called The Motech Network and his website is ClevelandWebDeveloper.com. In addition to building websites, Justin makes WordPress plugins and likes writing tutorials to help others learn about various aspects of web development.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">