Another Way to Avoid Writing Unnecessary :last-child's

About two weeks ago, I wrote a post on how you can use :not in your CSS to simplify life. Lots of people really liked the article, and I’m so glad! This method is pretty awesome.

One of our readers, Miler, wrote in to point me to this article that talks about the “lobotomized owl selector”. Funny name, but a fascinating approach, and quite honestly, way better.

In short, Heydon Pickering advises the following:

* + * {
  margin-top: 1.5em;

This particular approach makes so much sense, and I encourage you to read the full article. Essentially it adds margin only to the elements that have adjacent siblings. Heydon also uses the em here (which has its pros and cons) and demonstrates why this particular unit can be the right choice.

If we go back to the original example, each .post would already be correctly spaced, but to add our border, we’d do this:

.posts * + * {
  padding-top: .5rem;
  border-top: 1px solid #eee;

This only eliminates one line here, but possibly hundreds throughout our codebase.

As always, if you have questions or would like to discuss send me an email.

By Timmmmy

A human hoping to be empathetic and kind with all. I'm a geek, coffee drinker, stoner, maker of things, and forever an optimist. Brightly-colored clothes weren't enough, so I dye my hair too (he/him)

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s