Tag Archives: Class

Target and style an HTML element only if it has two classes

I was working with custom menus in my WordPress theme and assigned each menu item its own class so that I could have a custom background image.

This is basically how WordPress renders the menu (I simplified the number of classes in the example below, as WordPress generates a lot more than that):

1
2
3
4
5
6
7
8
9
10
11
<ul id="sub-menu">
    <li id="menu-item-12" class="custom-class-1 menu-item-12">
        <a href="#">Link 1</a>
    </li>
    <li id="menu-item-15" class="custom-class-2 menu-item-15">
        <a href="#">Link 2</a>
    </li>
    <li id="menu-item-18" class="custom-class-3 current-menu-item menu-item-18">
        <a href="#">Link 3</a>
    </li>
</ul>
<ul id="sub-menu">
	<li id="menu-item-12" class="custom-class-1 menu-item-12">
		<a href="#">Link 1</a>
	</li>
	<li id="menu-item-15" class="custom-class-2 menu-item-15">
		<a href="#">Link 2</a>
	</li>
	<li id="menu-item-18" class="custom-class-3 current-menu-item menu-item-18">
		<a href="#">Link 3</a>
	</li>
</ul>

So if I want to style the menu items at the sub-menu level, the only way to distinguish each menu item (without referencing ID numbers) is via my custom-class-#.

Now, what if I want to make the menu item appear differently if you’re on that page?

Fortunately, WordPress automatically creates a class called current-menu-item. If I were then to write a style like this:

1
2
3
4
5
6
7
.custom-class-1 a {
  color: #f00;
}
 
.current-menu-item a {
  color: #00f;
}
.custom-class-1 a {
  color: #f00;
}

.current-menu-item a {
  color: #00f;
}

Both those classes would have the same specificity and one would take over the other, depending on the order they were written. In a complex setup, this can get very messy, especially if you’re fiddling with a background image and its position.

Turns out, you can actually combine classes, in other words, define a multi-class union.

You can do that like so:

1
2
3
4
5
6
7
.custom-class-1.current-menu-item a {
  color: #f00;
}
 
.custom-class-1.current-menu-item a {
  color: #00f;
}
.custom-class-1.current-menu-item a {
  color: #f00;
}

.custom-class-1.current-menu-item a {
  color: #00f;
}

Now your style will only be applied if your HTML element has both of those classes. I never really had a need for this before today, as there was always another way, but this is good to know!