Sub topic 2
Layering Wider Layouts with `min-width` Queries
Assume you know basic HTML, CSS selectors, the box model, and basic Flexbox or Grid. A mobile-first stylesheet starts with narrow screens, then adds changes when the available width grows.
Layering Wider Layouts
Use a single-column base layout that works without media queries. Add wider layouts with min-width. This follows progressive enhancement: each wider screen receives extra layout rules instead of forcing a small screen to undo desktop styles.
.layout {
display: grid;
gap: 1rem;
padding: 1rem;
}
/* Add a second column when the content has room */
@media (min-width: 48em) {
.layout {
grid-template-columns: 2fr 1fr;
padding: 2rem;
}
}A desktop-first version would begin with two columns and use max-width queries to remove them. That approach often creates more overrides and makes the narrow layout harder to reason about.
Choosing Breakpoints from Content
A breakpoint is a width where the design needs to change. Choose it by watching the content, not by targeting a particular phone or tablet model.
Resize the page gradually. If navigation wraps, cards become too narrow, or a paragraph becomes difficult to read, add a breakpoint just before that failure. Use relative units such as em or rem so the layout responds when text size changes.
Fluid Layouts with Flexbox and Grid
Prefer fluid rules before adding more breakpoints. Grid can create as many columns as fit while preserving a useful minimum card width.
.cards {
display: grid;
gap: 1rem;
grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
}Flexbox is useful when items should share a row and wrap naturally. Grid is often clearer for two-dimensional card or page layouts.
Responsive Images and Media
Prevent images from overflowing their containers:
img {
max-width: 100%;
height: auto;
}Use srcset and sizes so the browser can select an appropriate file. The width and height attributes reserve space before the image loads.
<img
src="photo-800.jpg"
srcset="photo-400.jpg 400w, photo-800.jpg 800w, photo-1600.jpg 1600w"
sizes="(min-width: 48em) 50vw, 100vw"
width="800"
height="600"
alt="A hiker on a mountain ridge">Exercise
Why should a mobile-first stylesheet usually use min-width queries?
Show answer
It keeps the narrow layout as the default and layers wider-screen enhancements on top, reducing overrides.