When to use margin vs pading?

Margin collapses with neighboring items.

Padding gets the background color and contains the margin of child elements.

Consider in your layouts when you need an explicit amount of space, especially vertically stacked elements with a background color.

Margin on child elements will create a gap between the elements.

Margin can be used to space content in areas with different content, like forms or formatted text.

Use grid for this instead when you need consistent spacing.

The first and last child elements can add extra space on an element.

Remove it with :first-child { margin-top: 0 }.

Consider using only bottom margin to make spacing easier.

Private
Public
Topics