January 6, 2018
Solving my margin headache
An approach to dealing with margin between text elements in CSS
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
While this doesn't look awful, it introduces a couple of issues:
- The last paragraph in a section has an additional bottom margin.
- If you're like me and prefer more space between the last paragraph of a section and the next heading, you're out of luck.
:first-child & :last-child selectors
Second, I tried modifying my code to account for any edge cases using
This solves the issues introduced with the last approach. However, I can't help but get code smells, because:
margin-topis declared twice on heading elements
margin-bottomis declared twice on the paragraph element
:not(:first-child) & :not(:last-child) selectors
By combining the
:not selector with
:last-child, I was able to get rid of the excess code and land on my best approach yet.
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.