23 Apr 2016

The tilde CSS selector, use carefully!

A couple of the recent projects I’ve worked on have both had similar stylesheet problems. They have both misused the tilde selector, which has gone unnoticed and been the cause of numerous bouts of CSS bloat. You may well have come across this selector before. After all it’s a selector that’s been in the CSS spec for a long time, even IE7 supports it. Its purpose is to select all matching adjacent siblings.

An Obligatory Example

Example CSS and Markup
<ul>
<li class="something-important">Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>
.something-important {
   color: red;
}
.something-important ~ li {
   font-style: italic;
   color: grey;
}
Output
  • Item 1
  • Item 2
  • Item 3
  • Item 4

Here our tilde selector matches the sibling list elements after .something-important, namely items 2, 3 and 4.

So what’s the problem?

It is too easy to make brittle code.

In my experience the tilde selector is often used to select siblings by type rather than class. This makes it harder to know what the intention is. For example, .something-important ~ li doesn’t tell me anything about those target list elements, whereas .not-important applied to those list elements directly would instead have been much clearer.

The tilde selector is perhaps one of the least used of the relationship selectors. This has the result of requiring more of a developer’s thinking time to fully comprehend the rule’s effect. The worst usage I have seen involved some weird nested div setup. I think alarms bell should start ringing if you find yourself using the selector and it is not in a list context (with regards to markup or logical layout). Using the tilde selector on elements that aren’t in any sort of list is adding even more confusion. Perhaps you wanted the next sibling (+) selector instead?

Often a few extra keystrokes and applying a class to each item can be much clearer for future maintainers.

Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. Code for readability.

John Woods imparting some words of wisdom there.

Useful Usage

One use case I have seen before is utilising the tilde selector to style markup that was outside of the project’s scope. Markup that was produced by some third-party library, with very little in the way of classes and identifiers available. If you’re doing this, just make sure you put a big fat comment above the line to make its purpose clear. Or better yet, place it in your hacks/shame.css file.

Avoiding CSS Bloat

I think the lesson here is not so much to completely avoid the tilde selector, but rather that if you’re having CSS issues don’t start adding even more code. That’s almost never the route to a better maintained stylesheet or project.

CSS Dev
Back to posts