Welcome to the new Web Developer's Journal built with Nuxt Content!

CSS Margin and Padding

Margin is the spacing between elements, like heading and paragraphs. Browsers all have their defaults. For heading and paragraphs, the default is the font size for both margin-top and margin-bottom.

Centering with Margin

Setting the left and right margin to auto on an element will let you center it.

margin-left: auto;
margin-right: auto;

You can also do that in one step:

margin: 0 auto;

This sets the top and bottom margin to 0, and the left and right margins to auto. For margin-top and margin-bottom the auto actually means zero, so the most compact way to achieve the same result is:

margin: auto;

Collapsing Margins

If margins are not separated (they touch), they collapse together. That means that if you have two adjacent margins of e.g. 20px, the visible margin won't be 40px, rather only 20px. If one is bigger, you will get that as the final margin. For example, if one element's margin-bottom is 20px, and an adjacent element's margin-top is 30px, the space between them will be 30px.

What can separate margins? Borders and padding. Check out my post about the box model.

Margin Collapse Quirks

If you set a margin top on a heading inside a container, it's margin can merge together with the previous element. This can cause a situation when instead of pushing the heading down, you push down your entire container, just like if you'd have set that margin-top on the container. The solution is to set padding on the container first. Then you can apply margin inside it without having to worry about collapsing top margins.

Margins don't collapse in Flexbox and Grids.

Typography Best Practices

It's a well-known pattern to remove margin-top on typography related elements. That way we can use padding on the container.