CSS Tip: Use :not to Save Time and Lines of Code

I saw this tweet from Matt Griffin:

Finally started making my life easier by using :not(:last-of-type) rather than overriding with a separate :last-of-type rule. Huzzah!

Mind. Blown.

mind blown

Why didn’t I think of this earlier? This small thing saves so much time and lines of code. Let me explain. Let’s say you’re styling a list of posts.

<!-- This is what your html would look like -->
<ul class="posts">
  <li class="post">
    <a href="/link-to-post/" title="Permalink to post">
      <h2>Post Title</h2>
      <small>Thurs, Feb 16, 2017<small>
    </a>
  </li>
</ul>

This is how I foolishly used to style this. Foolishly I tell you!

.posts {
  list-style: none;
  margin: 0;
  padding: 0;
}

.post {
  border-bottom: 1px solid #eee;
  margin-bottom: .5rem;
  padding-bottom: .5rem;
  &:last-child {
    border-bottom: 0;
    margin-bottom: 0;
    padding-bottom: 0;
  }
}

Lots of code just to space each post evenly, except for the last one. This is what :not was made for!

.post:not(:last-of-type) {
  border-bottom: 1px solid #eee;
  margin-bottom: .5rem;
  padding-bottom: .5rem;
}

We’ve eliminated five lines of code here. Just imagine how much you’d save by using this throughout your code base! I made a CodePen for you to see this in action.

Hope this helps! If you have questions, send me an email to tim@theboldreport.net.

Those words be written good!