A few CSS handy tricks

January 15, 2021
views 1 min read

CSS was pretty much one of the first things I've started learning back in 2007. The evolution it took is completely mind-blowing.

Here are just a few tricks to color elements based on how a class start, ends or contains a keyword.


We'll be using the following HTML code to test what we're about to learn:

<div class="fancy-container">@telmo</div>
<div class="middle-content">@telmo</div>
<div class="third-party">@telmo</div>

Start

If we want to target a class that starts with a keyboard we can use ^ for that effect, such as:

[class^='fancy'] {
  color: tomato;
}

This will set the color of the first div to tomato.


Contains

To target an element that contains a keyword we can use *:

[class*='content'] {
  color: teal;
}

You see where I'm going with this don't you? Our second div will have a color of teal because it contains the word content.


Ends

Finally, to target an element that ends with a specific keyword we'll use $:

[class$='party'] {
  color: blueviolet;
}

Again, our third div will highlight with the beautiful color of blueviolet.

That's it ✌🏻

Read next
How to review pull requests
October 16, 2021
views