Dynamic styling for categories in Oxygen repeater (CSS only method)

If you use the Oxygen repeater element to query post categories then you may have wondered how to style these categories individually - here's how using CSS only!

I’ll be honest, I knew attribute selectors existed but I didn’t realise you can get very specific with them for elements where there are no clear classes or text. You can pretty much ignore my last 2 posts about styling category links in repeaters using jQuery or modifying core code and use this method instead!

The basic idea is that you can target an element based on the content of it’s attribute – in this case, the URL! For example, take the following:

a[href="https://mywebsite.com"] {
  color: red;
}

This will target all links (<a> tag) with the specific URL “https://mywebsite.com” and then make the text colour red.

However, in our case we are going to use a wildcard version of selector (purely for convenience, but I do recommend the above selector format) so it will look like the following:

a[href*="keyword"] {
  /*style*/
}

This will target all links containing whatever the partial keyword is in any part of the URL.

Basic setup

Just so I don’t accidentally target link items that are outside of my repeater, I will be a little more specific with the selector by adding a class to the repeater itself.

My HTML structure will look something like: Section > Repeater element (class=”post-repeater”) > Inner wrapper div > Date, Category, and Heading (all dynamic data and with links – this is very important in this case)

This will be queried across all post types (to learn more about this, I will have a post out soon).

Now we are ready to target the category links within the repeater using the a slightly modified version of the aforementioned link attribute selector. In my case it looks something like this:

/*For categories with links = wordpress*/
.post-repeater a[href*="/category/wordpress"] {
  background-color: blue;
}

/*For categories with links = oxygen*/
.post-repeater a[href*="/category/oxygen"] {
  background-color: purple;
}

Fine Tuning

Repeat the above format whilst changing the wildcard keyword in the URL. You can of course drop the “/category/” but I added this just to be a little more specific.

To be even more specific so this doesn’t target something else accidentally, you can use the very first example of the selector mentioned – so the CSS using my example should look something like this:

/*For categories with links = wordpress*/
.post-repeater a[href="https://bricks.farhan.app/category/wordpress"] {
  background-color: blue;
}

/*For categories with links = oxygen*/
.post-repeater a[href="https://bricks.farhan.app/category/oxygen"] {
  background-color: purple;
}

This method ensures you target a specific link within a specific parent.

To learn more about attribute selectors, checkout MDN Web Doc to learn more about this.

Let's talk.

Google reCaptcha: Invalid site key.