Responsive CSS Layout: Flexbox, Grid and Fluid Constraints
Learn a reliable mobile-first layout method and test at real viewport widths instead of copying arbitrary breakpoints.
Key Learning Objectives
- Explain the box model.
- Choose Flexbox for one-dimensional alignment and Grid for two-dimensional tracks.
- Use minmax and clamp for fluid layouts.
- Identify horizontal overflow at narrow widths.
Start with the smallest workable layout
Mobile-first CSS gives the default rules to a narrow screen and adds enhancements when space allows. This is a useful discipline because content, accessible controls and reading order remain usable before decorative complexity appears. Set box-sizing: border-box so the declared width includes padding and border. Avoid fixed widths for main content; use width: min(100%, 70rem) or max-width with padding. A layout that fits only one device is not responsive, even when it has media queries.
Use intrinsic Grid rather than guessing card widths
CSS Grid can create as many columns as space permits. minmax(min(100%, 16rem), 1fr) makes each card wide enough to read while preventing a minimum wider than the viewport. The outer min() is important on extremely narrow screens. Flexbox is better when elements mainly need to align in a row or column, such as an icon, text and button. Neither layout method replaces attention to readable text size and tap targets.
.cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
gap: 1rem;
}
.page { width: min(100%, 70rem); margin-inline: auto; padding: 1rem; }
.title { font-size: clamp(1.5rem, 2vw + 1rem, 2.5rem); }
Cards grow and wrap naturally, the page has a bounded readable width, and the heading scales within limits.
Debug overflow by looking for the responsible element
If a page can scroll sideways, a descendant may have a fixed width, a long unbreakable string, or an image exceeding its container. Use browser developer tools to locate the actual overflowing element. Set images to max-width: 100% and height: auto, and consider min-width: 0 for flex or grid children with long content. Do not hide all overflow on the body to conceal the bug; that can clip focus rings, menus and important content. Verify keyboard navigation after each layout change.
Build It: Responsive three-project portfolio
Create a portfolio with an accessible header and project cards that work from 320px to desktop.
Project Deliverables
- Semantic HTML for three projects.
- Mobile-first Grid styles using intrinsic sizing.
- A small testing log for 320px, 375px, 768px and desktop widths.
Acceptance Criteria
- No horizontal scrolling at tested widths.
- Images preserve their natural aspect ratios.
- All buttons and links remain keyboard-reachable.
Next Steps & Related Learning
This interactive lesson is part of the Frontend Developer curriculum. Continue exploring or try another interactive lesson: