How to target a specific row in a table via CSS

- by

This week I needed to make use of another CSS Pseudo element which is – like many of its colleagues – a rather sharp tool in the CSS toolbox.

I was using the eMember plugin for a membership site and wanted tweak the signup form. By default it looks like this (I’ve already removed a rather ugly looking border from the table):

Screen Shot 2014-03-28 at 17.12.01

The site I’m working on will provide a free membership, but that’s a technicality that users can’t change – and let’s face it the entire line reading “Membership: Free” could do with vanishing.

Rather than hack core files, I was able to override it with a CSS tweak and make it disappear. The problem is that this particular row in the table doesn’t have a class or ID to reference it.

CSS Pseudo Element nth-child to the rescue: with it, we can target a specific occurrence of the table row element (in our case, the fourth one down). Here’s how:

#wp_emember_regoForm table tr:nth-child(4) {
	display:none; 
}

This looks cryptic, I know – let me explain what’s happening here.

First we have an ID to target the specific area which is #wp_emember_regoForm. That’s the entire registration form though. In it, we drill deeper into table (which is the table shown above), and in it we have tr and td elements. td is a single cell, whereas tr is a whole row so we choose tr. Those are standard HTML elements.

But we don’t want to target every tr element in the table, we only want to target the 4th one down, hence we specify tr:nth-child(4). Had it been the second one, we would have said tr:nth-child(2).

Now all we do is set its display property to none, making it vanish without a trace. Here’s the final result – as if it never happened:

Screen Shot 2014-03-28 at 17.24.08

The nth-child selector can do other funky things, and you probably have seen it in action. Ever wondered how designers can make every other row in a table look slightly darker? Instead of a number, they use “odd” or “even”, targeting every other cell (starting with the first or second one):

table tr:nth-child(even) {
	background-color: #ddd;
}

nth-child even works with formulas, and of course you don’t have to target a table. Imagine making every other p tag disappear, or style every 3rd link in a different colour.

Have fun experimenting 😉



If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.