Sub topic 2
Wrapping Items onto Multiple Lines
Assume you know basic HTML, CSS selectors, the box model, and units such as rem and %. Flexbox lays items along one axis. When one line becomes too narrow, flex-wrap lets items move to another line.
Wrapping items with `flex-wrap`
A flex container uses flex-wrap: nowrap by default. Its direct children stay on one line and may shrink or overflow. Set flex-wrap: wrap to create additional flex lines.
Spacing items with `gap`
Use gap to add space between items and between wrapped lines. row-gap controls space between lines, while column-gap controls space between items in a line.
.cards {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}Unlike margins, gap does not add space around the outside edge of the container.
> callout tip > Wrapping happens only when the container has limited available space. A very wide container may keep every item on one line.
Starting size with `flex-basis`
flex-basis sets an item's starting size on the main axis. With the default row direction, it acts like a starting width.
Sharing extra space with `flex-grow`
After the starting sizes and gaps are accounted for, flex-grow determines how items share leftover space. An item with flex-grow: 2 receives twice as much extra space as one with flex-grow: 1 on the same line.
Handling overflow with `flex-shrink`
When a line is too narrow, flex-shrink determines how items surrender space. The default value is 1, so items can shrink. Set flex-shrink: 0 when an item must retain its basis, but remember that this can cause overflow.
<!doctype html>
<style>
.cards {
display: flex;
flex-wrap: wrap;
gap: 1rem;
max-width: thirtyrem;
}
.card {
flex-basis: 12rem;
flex-grow: 1;
flex-shrink: 1;
padding: 1rem;
background: #dbeafe;
}
</style>
<div class="cards">
<div class="card">One</div>
<div class="card">Two</div>
<div class="card">Three</div>
</div>Replace thirtyrem with 30rem before running the example.
Exercise
Which declaration allows cards to move to another line?
Show answer
flex-wrap: wrap.