CSS RegEx Attribute Selectors

horja
Image generated with Midjourney (AI)

Hello! Did you know that there are some RegEx-like features available in CSS, not only in common programming languages? Of course, CSS is not a programming language, even with the help of SCSS or LESS, but RegEx is not limited to programming, right?

By the way, always try to learn new things, not just about the world of programming, but about the entire world!

Be blessed to be a blessing!


What is RegEx?

When I was younger and in love with all kind of programming concepts (now I’m still younger and the passion is greater), I completed the RegEx problems from hackerrank.com.

As a side note, without any advertising, if you want to be in shape or to get in shape, I recommend you to choose some courses from hackerrank.com. You can choose other websites or even YouTube, but make sure you’re eager to learn new things.

So what does RegEx mean? RegEx comes from “Regular Expression” and is a custom expression (or code) made up of symbols that match a pattern.

Regular expressions are pretty flexible, in the sense that they can match a full pattern, not just a specific sets of characters.

Let’s take a look at some example.

Write a RegEx that matches the first three lines and skip the rest:

  • Match: Abc
  • Match: Bcd
  • Match: Cde
  • Skip: Def
  • Skip: Efg
  • Skip: Fgh

RegEx: [A-C][b-d][c-e]

What did I wrote? It’s not science fiction, nor music theory. Sometimes, musicians say that their sheets are not science fiction and scientists say that their work (science work) is not music theory to interpret the sound…

So, every group of brackets […] represents a single character.

The first group, [A-C], represents a single character from A to C (uppercase).

The second group, [b-d], represents a single character from b to d (lowercase).

And the last group, [c-e], represents a single character from c to e (lowercase).

That being said, in our example, with this RegEx [A-C][b-d][c-e], we can match the following words: “Abc”, “Bcd”, “Cde” and skip “Def”, “Efg”, “Fgh”.

I know it seems a little weird, but in programming, the logic is sine qua non, an indispensable condition to prove something. You can’t think without logic, right? Or can you?! Keep learning new things weekly! It’s for your greatness!

Let’s take a look at another example, much easier.

Write a RegEx that matches every word that starts with the letters “AB” from the following list:

  • ABnow
  • ABtest
  • ABlearn
  • yesterday
  • tomorrow
  • past

RegEx: ^(AB)

In this example, the caret symbol ^ is used for matching the start of the expression, and (AB) is a group of characters. So, with ^(AB) we match every word that starts with “AB”. Now it’s more easy for you to understand the usage of RegEx, isn’t it?

But is RegEx a useful thing to use in CSS? Every programming concept is welcome to be used in CSS, even if CSS is not a programming language.

RegEx is very powerful and has many other special characters. In (almost) any programming language you’ll find some types of RegEx.

In Linux (my beloved OS), there is the “grep” command, which stands for “global regular expression print” and it’s used to find a pattern in a text file.

Let’s get back to CSS.

So, in CSS, there are only few special RegEx characters that can be used to match a pattern.

Why do we need that? I know that it’s easier to style a CSS with a .class or an #id, but the more you know, the more fun you can have. Remember that!

In CSS, RegEx can be used to match the attributes on certain selectors. What kind of RegEx can we use? I will give you some tips for these:

  • selector[attribute=”exact-value”] (no special RegEx)
  • selector[attribute*=”certain-value] (* symbol to match a certain value)
  • selector[attribute^=”starting-value] (^ symbol to match a starting value)
  • selector[attribute$=”ending-value] ($ symbol to match an ending value)
  • selector[attribute~=”value-from-a-space-separated-list) (~ symbol to match a value from a space-separated list)
  • selector[attribute|=”value-from-a-dash-separated-list”) (| symbol to match a value from a dash-separated list)

Every difficult thing can be explained using something simple, right? Let’s do that!


Exact Value [attribute=”exact-value”]

When you search for a specific value, then you don’t need a RegEx for that. If you want to search for CSS on Google, you don’t need to invent the wheel.

Basically, this first example is a normal one and is by default. You’ll see a lot of examples in real life, especially when you’ll work with <form> tags, like <input> and <label>.

Consider the following:

See the Pen Exact Value [attribute="exact-value"] by horja musicology (@horja-musicology) on CodePen.

If you are not comfortable with HTML, don’t worry! HTML is a semantic language. It’s more important to learn CSS and to learn it very good, before moving on to JavaScript!

In that code snippet, you have two windows (or frames) with code and one with the result (the output).

For our interest, we’ll focus on the CSS one, but first I recommend you to take a general look to all of them.

In that CSS frame, the first CSS rule (we have two rules, a rule consists of a selector and a declaration block), all the <a> elements should have the blue color. All the <a> elements with the attribute “accesskey”, of course.

The second rule says that all the <a> elements with the attribute “accesskey”, who has the value “a”, should have the green color.

All this rules are 100% accurate as you can see the result.

If you are following this article from a PC (desktop or laptop), you can press ALT + A, ALT + B and ALT + C to open those links inside the “Result” frame.

Check out another example:

https://codepen.io/horja-musicology/embed/ZYzoqEW?default-tab=css%2Cresult

This example is much easier, right?

In this CSS frame, there is only one rule and it says that the color of all <a> elements with the value “https://www.robilinux.com” of attribute href should be green.

Now let’s start to use some RegEx symbols.


Certain Value [attribute*=”certain-value”]

The star symbol or more commonly known as the asterisk symbol (*) is used to search for a certain value in a string.

If we come back to the previous example, let’s change the CSS rule to match every element with the word “horjarobert” and to change its color to red.

https://codepen.io/horja-musicology/embed/ByBVVGX?default-tab=css%2Cresult

So, what did I do in that CSS rule? If I didn’t say (write) before, you need to know in this case that the selector is a (which defines a hyperlink), the attribute is href and the value of href is “horjarobert”. You can skip the quotes, but it’s a good practice to use them.

Therefore, we have a rule which says that whenever the condition is matched, the color of the link will be red. Our condition says that the value of the href attribute should contain the word “horjarobert”. Where? Anywhere inside a hyperlink.

That asterisk symbol is responsible for searching anywhere after the string “horjarobert”.

Consider another scenario: make every text inside an anchor element (<a>) who contains the letter “o” to have the green color.

I will consider the previous example. What do we need first? We’ll start with the a selector, then open the square bracket, put the href attribute, the asterisk symbol, the equal sign, the letter “o” between double quotes, the closing square bracket and finally, the declaration block.

Let’s see this practically.

https://codepen.io/horja-musicology/embed/zxOLPVm?default-tab=css%2Cresult

This example is pretty nice, right? Everything inside the <a> element, with the letter “o”, will be colored green.

Keep in mind that in a RegEx, the asterisk symbol is responsible for searching for a certain value inside a string.

Now let’s see what RegEx symbol can we use to search for a specific starting value. Before that, I have a simple question for you: how easy do you think CSS RegEx attribute selectors are? Thank you!


Starting Value [attribute^=”starting-value”]

When you want to search for a specific starting value (string or group of characters), you need the caret symbol ^. At the beginning of this article, we had such an example.

Now let’s dive into another example, this time with a CSS example. Let’s say that we want to have the color white for all <p> elements with the style attribute whom property begins with “background”.

https://codepen.io/horja-musicology/embed/emOLLyL?default-tab=css%2Cresult

What do you think about this example? Is pretty easy, right?

We used an inline style for every <p> element in HTML frame, then in CSS we have simple rule which says that for every <p> element with the style attribute, who starts with the value “background”, the color must be white.

You can think what will happen if the condition is never fulfilled. Well, in that case, nothing happens. Nothing, nothing? Absolutely.

Now let’s see this scenario: all hyperlinks that starts with “www” will have the yellow color and the background will be green; all other hyperlinks will be red with white background. We need two rules. Let’s see:

https://codepen.io/horja-musicology/embed/PwYdybE?default-tab=css%2Cresult

The first rule says that all <a> elements with the attribute href that starts with www will have the color yellow and the backround-color green. The second rule says that all <a> elements whould have the color red and the background-color white. Even if we reverse the rules, the result will be suitable for use.

Of course, the specificity is a concept that must be taken into account in CSS, but here it’s not the case because we have specific rules.

Before we go any further, let’s see an example with a pseudo-class. You can use pseudo-classes together with attribute selectors. I wan to create a rule in which every hyperlink who starts with “https” to have the color green.

How do we do that? Really simple: first of all, we need to select all <a> elements with the attribute href that starts with “https” and then a simple rule to avoid all hyperlinks that starts with “http:”.

https://codepen.io/horja-musicology/embed/PwYyqzJ?default-tab=css%2Cresult

It is hard to use pseudo-classes along with attribute selectors? Not really! If you understand the basics, you will do great things!

Therefore, if we have a RegEx that match a starting value, it is logical to have a RegEx that match the final value from a string. Next we’ll use the $ symbol.


Ending Value [attribute$=”ending-value”]

I think this article has a lot of examples. Is that okay? Absolutely!

With the dollar sign, $, you can match a pattern when searching for an ending value. From the previous example, let’s change the color of the hyperlink who ends with “.com” to red.

https://codepen.io/horja-musicology/embed/KwPGRBy?default-tab=css%2Cresult

This RegEx type is useful when you want to stylize different documents, like images or files. With $ symbol you can match directly the extensions.

Check out this example: put a 20px border-radius on all images with the.png extension.

https://codepen.io/horja-musicology/embed/dPbgewy?default-tab=css%2Cresult

I like a lot this example! It highlights the power of RegEx with the $ symbol.

In practice, you’ll encounter many other examples of RegEx, but if you know how to use *, ^ and $, you will do great things.

Do you want to be a professional CSS designer? Then you need to know more about CSS RegEx attribute selectors!


Space-Separated Value [attribute~=”value-from-a-space-separated-list”]

The tilde ~ symbol is used when you want to search for a value who is separated by spaces.

It’s not a common practice to use ~= operator, but never know when some “guru guy” want to impress his boss and try to write some irrelevant CSS rules.

In some cases, we can use the * operator to search for words (strings), but when there are values separated by spaces, the ~ is more efficient.

I don’t have a relevant example to show you, but I want to give you two easy examples. Let’s consider the following HTML code:

<p class=”one two three” rel=”website business friend”>This article is very powerful in knowledge. Thank you!</p>.

Now let’s use the ~= operator to create a CSS rule:

  • p[class~=”two”] { color: green; }
  • p[rel~=”business”] { color: yellow; }

What does these rules mean? The first rule says that all <p> elements with the attribute class who match the value “two” should be green. The second rule says that all <p> elements with the attribute rel who has the value “business”, should be yellow.


Dash-Separated Value [attribute|=”value-from-a-dash-separated-list”]

Another example of using RegEx in attribute selectors is when we want to search for a starting value separated by dashes. In this case we use the pipe | symbol.

As in the previous case, the |= operator is not pretty common, but it’s good to know about it.

Here I can give an example: search for all <p> elements that have the attribute style and include the property background. When the rule is fulfilled, the text must be italicized.

https://codepen.io/horja-musicology/embed/LEPgrQZ?default-tab=css%2Cresult

Remember that the pipe | symbol is for matching the starting value of an attribute that has a dash (or more)! Thank you!


Multiple Attributes [attribute=”value-1″][attribute=”value-2″]

Do you want to match different attributes in the same rule? You can do that! How? Very simple! Use multiple attributes.

Let’s take a look at this scenario: I have four paragraphs with title attribute and each one has a specific color (red, green, blue, orange). Write a rule to make the background-color to yellow for that paragraph who has the color green. How do you think? It’s easy?
https://codepen.io/horja-musicology/embed/raBQOPy?default-tab=css%2Cresult

In our CSS rule we are searching for the value “paragraphB” of the title attribute, then take a look at the style attribute who has the green color. I use the asterisk * symbol to match the certain value (“green” in our case).

You can play around with other examples. In coding, sky is the limit.


Matching Case-Insensitive Values

The last example or concept is that you can specify to match a pattern as case-insensitive. How? By putting the “i” letter inside the attribute selector (inside the brackets).

Let’s say that we have three title attributes with the following values: title, Title, TITLE. We need to match all paragraphs with these values and make them to be green. Can we do that without writing three rules, but only one? Of course!

https://codepen.io/horja-musicology/embed/xbKQwNp?default-tab=css%2Cresult

The rule is very simple. Just put that “i” letter and it will indicate that the pattern should be case-insensitive.


Try & Learn

If there is something that you didn’t understand, please let a comment below and I’ll try to give you a valuable response.

Do you want to become a great CSS designer? Then you must to try all the examples, create other and learn the basics! Everything becomes easy once you understand the basics.

God bless you!

Share This Article
Leave a Comment