DEV Community

Eva - includeJS.dev 🎈
Eva - includeJS.dev 🎈

Posted on • Originally published at includejs.dev on

CSS and Spacing πŸ“

My notes from the excellent article on Spacing in CSS by @shadeed9 πŸ’ͺ.

Spacing can be divided into two groups:

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

What's a margin collapse?

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

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

Learn about Right to Left styling.

Gaps in Flexbox layout

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

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

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

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.

Top comments (0)