Flexbox
Arrange related items along a main axis with suitable sizing and wrapping.
CodeBhavyaArrange content with clear axes, shared tracks and responsive changes learners can use.
Level 12 measured the space a box needs. This lesson organizes several boxes into useful layouts. You will choose Flexbox or Grid, reason about axes and tracks, use flexible sizing and adapt a page when the viewport becomes narrower.
The goal is a workshop resource collection that remains readable and operable across screen sizes. You will compare actual rendered examples in a local preview, preserve the source order, and explain why a layout wraps, shrinks or overflows.
Arrange related items along a main axis with suitable sizing and wrapping.
Define tracks and place content in a consistent row/column arrangement.
Adapt to available space and test intermediate widths, not only named devices.
Keep readable content, meaningful order and visible keyboard focus.
Flexbox focuses on arranging items along a main axis. It is useful for action groups, navigation items and a row or column of related content. Grid focuses on a track system across rows and columns, making it useful when the columns should align across several rows.
A wrapping flex container can have several lines, but each line distributes its available space independently. A grid can keep a shared column structure across its rows. Neither tool replaces semantic HTML or guarantees accessibility merely because a particular display value is present.
You can combine them. A resource collection can be a grid, while the actions inside each card use flex. Start with the relationships the content needs instead of forcing the whole page into one layout method.
Shared columns organize the larger collection.
Buttons share an axis and wrap when needed.
Paragraphs grow naturally with the explanation.
Applying display: flex or display: grid changes the layout of that element’s direct items. The container controls the overall arrangement. The items can have their own sizing or placement rules. Grandchildren do not all become items in the outer container just because they are nested somewhere within it.
<div class="actions">
<button type="button">Inspect</button>
<button type="button">Reset</button>
</div>
.actions { display: flex; gap: 12px; }In this example, the two buttons are flex items. If you wrap both buttons in another div, that wrapper becomes the direct item unless you also choose a layout for the wrapper. Inspect the actual structure when a layout rule appears to affect the wrong element.
Keep the HTML purpose intact. A nav can be a flex container, and an article collection can use grid. The display value describes layout rather than deciding what the content means.
Flexbox has a main axis and a perpendicular cross axis. Flex-direction chooses the main axis: row follows the inline direction and column follows the block direction. In a typical left-to-right horizontal writing mode, a row runs horizontally and a column runs vertically.
This is why “justify-content is horizontal” is an unreliable rule. Its meaning follows the main axis. When flex-direction changes, the physical direction of the main axis changes too. Direction and writing mode can also affect which physical edge is the start.
.actions { display: flex; flex-direction: row; }
.steps { display: flex; flex-direction: column; }Items progress along the inline direction.
Items progress along the block direction.
Perpendicular to whichever main axis was chosen.
Justify-content distributes items or space on the main axis when there is space to distribute. Align-items sets the cross-axis alignment of the items in a line. Align-self can adjust an individual item’s cross-axis alignment.
Align-content concerns the distribution of flex lines in a multi-line container with appropriate extra cross-axis space. It is different from align-items. A single line with no relevant extra space may not show the effect you expected.
Auto margins and flexible growth can consume space before a distribution keyword has much visible work to do. When center or space-between appears ineffective, inspect the actual free space and item sizing before changing the property name.
.toolbar {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}This toolbar example assumes a row in ordinary horizontal writing mode. Center aligns items across that row; space-between distributes any relevant remaining main-axis space.
The default flex-wrap value is nowrap. Items remain in one flex line; they may shrink according to their sizing rules, or overflow if their constraints prevent fitting. Flex-wrap: wrap allows additional lines. It does not make long text inside each item automatically safe.
Gap supplies separation between items or lines. It is easier to maintain than manually assigning several asymmetric child margins for a simple action group. A gap still consumes layout space, so include it when predicting whether several items can fit.
.actions { display: flex; flex-wrap: wrap; gap: 12px; }
.actions > button { flex: 0 1 auto; }A wrapped row should have enough room for its meaningful controls and labels. Try a longer label as well as a smaller viewport. Do not shrink the font until the action is unreadable merely to keep every button in one row.
In the lab, a deliberate non-wrapping row uses fixed item bases so you can observe overflow. That case is a comparison, not a recommended default for a narrow learning page.
Flex-basis supplies a starting main size for flex sizing. Flex-grow describes how positive free space is distributed. Flex-shrink participates in distributing negative free space; its effect also depends on the basis and applicable minimum constraints. These factors are not promises of a final fixed width.
The flex shorthand combines those decisions. Writing the three parts explicitly helps a beginner explain the behavior. In flex: 1 1 140px, the item can grow, can shrink and begins from a 140px basis before the algorithm resolves the layout.
.resource { flex: 1 1 140px; min-width: 0; }
.fixed-action { flex: 0 0 8rem; }The fixed-action example deliberately neither grows nor shrinks from its basis. Use that choice only when its content and surrounding space support it. Equal growth factors do not always make final widths equal when starting bases or constraints differ.
A basis of auto can use a relevant main-size property or content according to the applicable sizing rules. Avoid treating flex-basis as simply another spelling of min-width.
A flex or grid item’s automatic minimum can be influenced by its content. A long unbroken token may prevent the item from shrinking as expected. A targeted min-width: 0, suitable wrapping or a local scroller can help, depending on the content.
Use overflow-wrap: anywhere for a token that may break without losing its purpose. A code sample or data table may instead need a local horizontal scroller. Do not globally clip every card to hide the overflow.
Flex order, reversed directions and Grid placement can change the visual arrangement. They do not automatically provide an equally useful reading or keyboard order. Put the meaningful sequence in the document first, then use layout for presentation.
.resource { min-width: 0; }
.resource .identifier { overflow-wrap: anywhere; }In the lab, cards remain in source order 1 through 6 for every scenario. Use keyboard navigation through their disclosure summaries to compare that sequence with the visual arrangement.
A grid container defines a track arrangement. A column track is the space between adjacent column lines; a row track is the space between adjacent row lines. Grid-template-columns declares explicit column tracks, while grid-template-rows can declare explicit row tracks.
If you supply three columns and enough items for more than one row, automatic placement can create additional rows. Explicit tracks and automatically created tracks are related but different parts of the grid. Do not assume a three-column declaration limits the collection to exactly three items.
.resources {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 12px;
}This example requests three shared columns across the rows. Under the applicable sizing conditions, each 1fr track takes an equal share of the available flexible space after other relevant contributions such as gaps. The minmax lower bound helps avoid an automatic minimum unexpectedly holding the track open.
Tracks are bounded by lines. An item can be placed between lines or span a number of tracks. For a three-column grid, there are four boundary lines across those explicit columns. The gap is spacing between tracks, not a separate content column.
Named areas can make a small page structure readable, such as a header, main content, related panel and footer. They should describe the intended layout while the HTML source remains meaningful. A named area in a template must form a valid rectangular region.
.featured { grid-column: 1 / -1; }
.layout {
display: grid;
grid-template-areas: "main aside";
grid-template-columns: minmax(0, 2fr) minmax(0, 1fr);
gap: 16px;
}
.main-panel { grid-area: main; }
.related-panel { grid-area: aside; }In the simple explicit-grid example, 1 / -1 spans from the first to the last explicit grid line. When adapting the layout, preserve the logical source sequence rather than using placement to conceal a poorly ordered document.
The fr unit represents a share of flexible grid space. It is not “one fraction of the entire viewport.” The available space is affected by the container, fixed tracks, gaps and the sizing algorithm.
Minmax defines a lower and upper track sizing bound. A common flexible pattern is minmax(0, 1fr), which allows the track’s lower bound to be zero. The item’s own content and overflow behavior still require attention.
.two-columns {
display: grid;
grid-template-columns: minmax(0, 1fr) minmax(0, 2fr);
gap: 16px;
}If the simple definite-size case has 600px available inside the container and one 16px gap, there are 584px left for these flexible shares under the stated uncomplicated conditions. The 1fr and 2fr tracks divide that flexible space in a 1-to-2 relationship. This arithmetic does not describe every intrinsic-size case.
Avoid declaring several percentage columns that already consume 100% and then forgetting the gaps. Inspect the actual available track space when a row unexpectedly becomes wider than its parent.
Repeat can create tracks automatically based on how many fit. Auto-fill keeps the generated track slots, including empty ones in the relevant case. Auto-fit collapses eligible empty repeated tracks after placement so occupied tracks can use the space. With enough items to occupy the slots, the difference may not be visible.
Choose a sensible minimum so cards remain readable. A minimum wider than the narrow container can itself cause overflow. The following pattern limits the minimum to the container width when the available space is smaller than the preferred card minimum.
.resources {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 14rem), 1fr));
gap: 16px;
}Test the resulting collection with few items as well as many items. Automatic tracks reduce the need for some width breakpoints, but they do not replace all responsive decisions, such as menu behavior, typography or the handling of a large data table.
Responsive design adapts a useful page to the available space and interaction context. Include the viewport metadata for ordinary mobile page sizing. Then use flexible components, constraints and appropriate layout changes rather than a collection of unrelated fixed-width pages.
<meta name="viewport" content="width=device-width, initial-scale=1">
.page { width: min(100% - 2rem, 70rem); margin-inline: auto; }
img { max-width: 100%; height: auto; }Do not disable zoom to make a layout seem fixed. Enlarged text and zoom can change the effective space available to the page. Inspect whether controls wrap, text remains readable and content can still be reached.
A viewport width is a CSS measurement context, not a dependable label for the device model or input method. A wide window can be resized, and a device can use a different orientation. Choose responsive rules according to where the content needs a change.
A media query applies its rules when the stated condition matches. A minimum-width condition can build from a simple narrow layout toward wider arrangements. A maximum-width condition can adapt a wider default downward. Keep the conditions and rule order understandable.
.resources { display: grid; grid-template-columns: 1fr; gap: 12px; }
@media (min-width: 341px) {
.resources { grid-template-columns: repeat(2, minmax(0, 1fr)); }
}
@media (min-width: 521px) {
.resources { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}These boundaries are teaching values for the lab, not universal phone and tablet sizes. If two conditions match, the cascade still resolves competing declarations. In this example the later wider rule supplies three columns once its condition matches.
Test at the boundary and on either side of it. A collection that looks correct at 320px and 1000px can still have an awkward transition between them. Media queries query the relevant media environment, which for the lab preview is its own frame viewport.
A responsive review includes more than the number of columns. Check readable text, growing explanations, focus visibility, menus, long content and the order of interactive elements. Do not hide essential information at small widths to make the screenshot look simpler.
Respect reduced-motion preferences where animations are unnecessary for understanding. A transition can become immediate while the state change still works. The shared interview cards in this course keep their question/answer behavior when the animation is reduced.
Use hover as an enhancement rather than the only way to reveal essential content. A keyboard or touch user still needs a usable route. Keep native controls, labels and visible focus when the layout changes.
@media (prefers-reduced-motion: reduce) {
.card-motion { transition: none; }
}The rule targets motion that you control. It does not prove the whole page is accessible or every third-party component respects the preference. Verify actual tasks and record the checks you performed.
Follow the source order, grid choice and matching viewport rules. Use the same numbered timeline and playback controls as the previous lessons. The last stage asks you to verify content and keyboard use as well as the visual arrangement.
Six resource cards appear in document order 1 through 6.
HTML order: 1 → 2 → 3 → 4 → 5 → 6A useful reading and keyboard sequence is the foundation. Layout must not be used to repair an illogical source order.
Compare wrapping Flexbox, deliberate non-wrapping Flexbox, a fixed three-column Grid and a responsive Grid. The preview is a separate local document containing six cards in a stable source order. Change its actual frame width to compare how the CSS responds.
If the selected preview is wider than your lesson panel, scroll horizontally in the preview wrapper. This keeps the chosen teaching viewport rather than silently shrinking it. The fixed grid and non-wrapping flex cases are deliberately useful comparisons; they may be awkward on narrow widths.
The responsive Grid uses one column at 240px, two at 420px and three at 640px under its stated rules. The explanation describes expected behavior of the fixed examples; it does not read or certify the browser’s entire layout.
Default responsive Grid preview at 640px.
Confirm the intended display value and which elements are direct items.
Inspect basis, tracks, gaps, minimums and available container space.
Check the actual viewport and which media-query rules match.
Test reading sequence, keyboard focus, content growth and local scrolling.
If a flex action row does not wrap, check flex-wrap and item constraints. If a grid collection is wider than its parent, check fixed track minimums, unbroken content and the contribution of gaps. If a breakpoint has no effect, inspect its condition, selector and the later competing rules.
When visual order changes, verify that the intended task can still be followed by keyboard. If long text overlaps, inspect fixed heights and overflow. Prefer a targeted correction to globally hiding content or reducing every font size.
Use browser tools to inspect the actual layout and computed declarations. The lab’s expected-result text supports a guided comparison; a real project needs its own measured review.
Each flex line distributes its space independently. Grid can keep shared column tracks aligned across several rows.
No. In Flexbox it follows the main axis, which depends on direction and writing mode.
Align-items concerns items in a line; align-content concerns the distribution of lines in a multi-line flex context with relevant extra space.
No. It supplies a starting size before growth, shrinking and constraints determine the result.
It gives the track a zero lower bound instead of an automatic minimum. The item’s content and overflow still need appropriate handling.
Auto-fit can collapse eligible empty repeated tracks after placement; auto-fill keeps generated slots. With no empty slots their result may look similar.
No. Put the meaningful sequence in the HTML and verify the actual reading and focus paths.
Choose where the content needs a useful layout change and test around that boundary, rather than assuming one universal device size.
Change a row to a column. Expected: the main axis changes; explain alignment using axis names rather than only horizontal/vertical.
Use six fixed 140px items with gaps, then compare wrapping and non-wrapping. Expected: the non-wrapping case needs enough width or access to overflow.
Use a three-column grid with six cards. Expected: two rows share the same column structure under the fixed-track example.
Test responsive Grid at 240px, 420px and 640px. Expected: one, two and three columns respectively.
Test just below and above the lesson’s 341px and 521px minimum-width conditions in a standalone browser example. Expected: the matching rule changes at its boundary.
Place a long resource identifier inside a card with suitable wrapping. Expected: it remains available without pushing the whole page wider.
Tab through the six native disclosure summaries. Expected: source sequence 1–6 stays meaningful at each width.
Compare auto-fill and auto-fit with fewer items than available tracks. Expected: eligible empty tracks behave differently; describe the actual inspected result.
An element establishing a Flexbox layout for its items.
The axis along which flex items are arranged, determined by direction.
The axis perpendicular to the flex main axis.
The starting main-size basis used during flex sizing.
The area between adjacent grid lines, forming a row or column.
A share of flexible grid space, written fr.
A condition controlling when a set of CSS rules applies.
A chosen condition boundary where the layout or presentation changes.
The viewing area used by the relevant document’s media and layout context.
The adaptation of content arrangement as available space or presentation changes.
Build a semantic workshop resource page with six article cards. Keep their source order meaningful. Use Grid for the collection and Flexbox for each card’s action group. Make the narrow default readable, then add wider conditions only where the collection needs more columns.
Use sensible gaps, minimum-size handling, flexible text panels and visible focus. Include a long identifier and a longer explanation in one card. Keep essential information and controls available at every width; do not use CSS reordering as a repair for an illogical document sequence.
Test at 240px, 420px and 640px for the teaching conditions, then test nearby and intermediate widths in your own browser. Try zoom, enlarged text and keyboard navigation through native controls. Record one actual finding and the correction that resolves it.
Success criterion: explain why Flexbox and Grid were chosen, identify the matching responsive rules, demonstrate stable keyboard order and preserve readable content. The next lesson introduces JavaScript fundamentals for adding behavior.
Before marking complete, build a wrapping action group, a track-based collection and a responsive change you can explain. Test a long token and a keyboard path at more than one width. Completion is a local study milestone, not an assessment score.