Sub topic 1
What Responsive Design Is and Why It Matters
Responsive design lets one web page adapt to different screen sizes and device capabilities. The layout can change from one column to several columns, while text, images, and controls remain usable. CSS media queries apply styles only when selected conditions are true.
Prerequisites
Assume you know basic HTML structure, CSS selectors and properties, the cascade, the box model, and common units such as px, em, and rem.
A responsive page should remain readable without requiring horizontal scrolling. It should also work with touch input, keyboards, and screen readers. Design for the content and available space rather than for named devices.
Setting the viewport
Mobile browsers often render a page using a wide virtual viewport and then scale it down. Add this element inside the document’s <head>:
<meta name="viewport" content="width=device-width, initial-scale=1">width=device-width makes the layout viewport match the device width. initial-scale=1 sets the initial zoom level. Without this element, width-based media queries may appear to use an unexpectedly large width on phones.
Anatomy of a media query
A media query begins with @media, followed by a condition and a block of CSS declarations:
@media screen and (min-width: 40em) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}screen is the media type. The and operator connects it to the min-width feature. The rule applies when the layout viewport is at least 40em wide. If the condition is false, the declarations inside the block do not apply.
Querying the viewport width
Width features are the most common responsive conditions:
min-widthapplies at or above a width.max-widthapplies at or below a width.widthmatches an exact range condition.
Start with a simple layout, then add rules when the content needs more room:
.cards {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@media (min-width: 40em) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}Exercise
Why can a media query appear to fail on a phone when the viewport meta tag is missing?
Show answer
The browser may use a wider virtual layout viewport, so the width condition does not match the device’s visible width.