Avoid CSS margin confusion

I wrote this in a comment on GitHub the other day and realised it’s something I’ve been doing subconsciously for ages that makes CSS easier for me. Maybe it’ll help you too!

I’ll let you in on a secret: I haven’t used margin-top or margin-left in CSS for years.

Consequentially, it’s also been a while since I’ve used negative margins or thought about collapsing margins.

Generally, we lay out elements on a web page in one direction: from the top left corner to the the bottom right corner.

elements laid out from the top left corner to the bottom right corner

I find thinking about space between elements in those same directions is intuitive and easy.

elements laid out from the top left corner to the bottom right corner, with arrows between them in the same directions

At least, I find it a zillion times easier than this…

elements laid out from the top left corner to the bottom right corner, with arrows between them in all directions

…and that doesn’t even take negative or collapsing margins into account.

Pretend that margin-top and margin-left don’t exist and I promise your CSS life will get easier!