Gap & Ordering
Overview
Historically, spacing out flex children required a nightmare of margin-right: 10px on everything, and then using pseudo-classes (:last-child { margin-right: 0 }) to remove the margin from the very last item so it wouldn't break the layout. The gap property completely annihilated this problem. It acts as 'intelligent padding', only placing space between the elements, never on the outside edges. Additionally, the order property allows you to completely rearrange the visual rendering of children without touching the HTML.
Syntax
/* --- GAP (Applied to the Parent) --- */
.card-container {
display: flex;
/* Creates a precise 20px space strictly BETWEEN items */
gap: 20px;
/* You can specify Axis-specific gaps! (Row-gap, Column-gap) */
gap: 10px 30px; /* 10px vertical between wrapped rows, 30px horizontal */
}
/* --- ORDER (Applied to the Child) --- */
.child-a {
/* Default order for all elements is 0.
Lower numbers visually render first! */
order: 2;
}
.child-b {
order: 1; /* Renders BEFORE child-a, even if it's lower in HTML! */
}
.child-important {
order: -1; /* Instantly snaps to the absolute front of the line! */
}Common Pitfalls
- Using
margininstead ofgapin modern Flexbox. Using margins for component spacing in a flex container is obsolete and leads to buggy math when items wrap.gapis mathematically perfect and requires zero hacky resets. - Abusing the
orderproperty for accessibility.orderONLY changes the visual paint on the screen. A blind user using a Screen Reader, or a power user hittingTab, will still navigate the elements in the original HTML order. If you useorder: -1to move a Submit button to the top of a form visually, the user's Tab key will jump wildly around the screen.
Interview Questions
order property to fix a poorly structured HTML document?Because CSS order causes a severe disconnect between the Visual DOM and the Accessibility Tree. Keyboard focus and Screen Readers strictly follow the raw HTML source order, resulting in a completely broken, confusing experience for disabled users if the visual order doesn't match.
Real-World Example
Using gap to create a perfect form layout instantly.
.form-group {
display: flex;
flex-direction: column;
/* Perfect, uniform spacing between the Label, Input, and Error Message,
without writing a single margin! */
gap: 8px;
}Check Your Knowledge
Test your understanding of Gap & Ordering with these quick questions.