Stop Using CSS Margin And Padding Shorthands. Use This Instead
Why the most common properties in web design became so complicated and what we can do to make space easier and less error prone
Lately I’ve started to share some CSS tips, like this and that. Today I’d like to tell you a little bit about what I think about margin and padding shorthands and why you shouldn’t use them.
We all love shortcuts. Shortcuts mean we can go faster into the desired place. I can’t find a better proof I like shortcuts too than that I’ve designed desk mats with keyboard shortcuts for IntelliJ IDEA and VSCode.
This article was brought to you thanks to 18k readers on Medium.
CSS also offers shorthands. Two commonly used shortcuts are these for margin and padding:
margin: 2px;
margin: 2px 4px;
margin: 2px 4px 6px;
margin: 2px 4px 6px 8px;
Shorthands for padding look like the same. It is hard to notice what these values mean. Before I’ll jump into it, just a reminder of full name properties:
margin-left: 2px;
margin-right: 4px;
margin-top: 6px;
margin-bottom: 8px;
The values I’ve provided in this example doesn’t correspond with the previous examples. Because shorthands have this structure:
margin: 2px (all margins); // SHORTHAND 4
margin: 2px (top and bottom) 4px (left and right); // SHORTHAND 3
margin…