Categories
Code

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 smith@ttimsmith.com.

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:

WordPress.com Logo

You are commenting using your WordPress.com 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