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
toinline-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)