Skip to content

CSS and Spacing

From the article: Spacing in CSS

Written by Eva Dee on (about a 2 minute read).

Spacing can be divided into two groups:

  • inner spacing (padding)
  • outer spacing (margin)

What's a margin collapse? permalink

Margin collapse happens when two vertical elements have a margin, and one of them has a greater margin than the other. In that case, the greater margin will be used, and the other will be ignored.

🔨 To fix: Use a single direction margin, e.g.:

.element:not(:last-child) {
margin-bottom: 1rem;
}

🤔 If both the parent and the child have a margin, the child's margin will be collapsed.

🔨To fix:

  • Add a border to the parent element OR
  • Change the child element display to inline-block OR
  • Add padding-top to the parent element.

Padding is not working permalink

Vertical padding doesn’t work with elements that have display: inline, like <span> or <a>.

🔨 To fix: need to do display: inline-block;

RTL Styling permalink

Learn about Right to Left styling.

Gaps in Flexbox layout permalink

Flexbox doesn't have a gap property, like grid-gap.

🔨 to fix:

  • Add padding-left to the grid item AND
  • Add a negative margin-left with the same padding-left value to the grid parent.

The reason: because the first card has padding-left while in reality it’s not needed. So it will push the wrapper to the left and cancel that unneeded space (Demo).

Margin bottom permalink

The last element should not have a bottom margin, as margin should only be between elements.

🔨 To fix: cancel the unneeded spacing by adding a negative margin to the parent element.

vmin permalink

Viewport Minimum (vmin) – A percentage of the viewport width or height, whichever is smaller. 10vmin will resolve to 10% of the current viewport width in portrait orientations, and 10% of the viewport height on landscape orientations.

vmax permalink

Viewport Maximum (vmax) – A percentage of the viewport width or height, whichever is larger. 10vmax will resolve to 10% of the current viewport height in portrait orientations, and 10% of the viewport width on landscape orientations

  • grid-gap: min(2vmax, 32px);

Use a gap equal to 2vmax, but it shouldn’t go above 32px.