January 6, 2018

Solving my margin headache

Throughout my attempted mastery of CSS, one of my most significant pain points has been dealing with margin between text elements. In this post, I will go over some of my previous approaches and the one approach I eventually landed on.

Bottom margin only

First, I tried limiting myself to only using margin-bottom.

See the Pen Example #1 - Bottom margin only by Taylor Bryant (@taylorbryant) on CodePen.

While this doesn’t look awful, it introduces a couple of issues:

:first-child & :last-child selectors

Second, I tried modifying my code to account for any edge cases using :first-child and :last-child selectors.

See the Pen Example #2 - :first-child & :last-child selectors by Taylor Bryant (@taylorbryant) on CodePen.

This solves the issues introduced with the last approach. However, I can’t help but get code smells, because:

  1. margin-top is declared twice on heading elements
  2. margin-bottom is declared twice on the paragraph element

:not(:first-child) & :not(:last-child) selectors

By combining the :not selector with :first-child and :last-child, I was able to get rid of the excess code and land on my best approach yet.

See the Pen Example #3 - :not(:first-child) & :not(:last-child) by Taylor Bryant (@taylorbryant) on CodePen.


If you ever find yourself writing more CSS just to undo previous rules, it’s probably worth giving :not a shot. After my margin epiphany, I see myself applying this same concept to other aspects of my CSS every day.

Other Posts