- Learn
- Computer Science & IT
- Programming
- Web Development Basics
- Responsive Web Design
Responsive Web Design: Viewports and Media Queries
srcset, sizes and <picture>, and test pages across widths, zoom levels, touch input and reader preferences.BeginnerLesson 6 of 8 in Web Development Basics Course
What you will learn
- Explain what responsive design is, make mobile browsers lay out a page at the device's real width, and size text and boxes with units that scale.
- Explain responsive design and set the viewportDescribe what responsive design does, how CSS pixels relate to device pixels, and why every responsive page needs the viewport meta tag.
- Size text and boxes with relative unitsUse percentages, em, rem and ch so that boxes follow their container and text follows the reader's font-size setting.
- Use viewport units and fluid sizingSize elements against the viewport with vw, vh and the newer small, large and dynamic units, and set limits with min(), max() and clamp().
- Explain responsive design and set the viewport
- Write media queries, build styles mobile-first with breakpoints chosen by the content, and turn flexbox and grid layouts into layouts that adapt to the screen.
- Write media queriesUse media types, width conditions, logical operators and other media features, and place media queries correctly in the cascade.
- Build mobile-first with content-based breakpointsWrite base styles for small screens, add min-width queries as space grows, and place breakpoints where the content needs them.
- Make flexbox and grid layouts responsiveChange layouts at breakpoints, and use intrinsic grid and flexbox patterns that adapt without any media query.
- Write media queries
- Declare query containers, style components with container queries and container units, and choose between media queries, container queries and intrinsic layouts.
- Set up containers and write container queriesDeclare a query container with container-type, write @container rules, name containers and avoid the common setup mistakes.
- Size with container units and choose the right toolUse container query units for sizes that follow a container, and decide when to use a media query, a container query or an intrinsic layout.
- Set up containers and write container queries
- Keep images and embedded media inside their containers, let the browser choose a suitable file with srcset and sizes, and change the crop or format with the picture element.
- Make images and embedded media flexibleStop images and videos from overflowing, keep their proportions, reserve space before they load, and control cropping with object-fit.
- Let the browser choose an image size with srcset and sizesOffer the same image in several files, describe how wide it is displayed, and predict which file the browser loads.
- Change the crop or format with the picture elementUse picture and source to show a different crop at different widths or to offer modern image formats with a fallback.
- Make images and embedded media flexible
- Check pages across widths, zoom levels and real devices, find and fix overflow, and adapt to touch input and the reader's settings.
- Test across widths and fix overflowUse the browser's responsive design tools and real devices, check reflow at 320 CSS pixels, and track down the causes of horizontal scrolling.
- Design for touch, zoom and user preferencesSize controls for fingers, avoid hover-only interactions, support zoom and orientation, and respond to reduced motion, color scheme and print.
- Test across widths and fix overflow
Responsive Web Design study guide
1Prepare a page to adapt to any screen
Good responsive behavior starts with the space the browser thinks it has and the reference each size follows. Set up the mobile viewport, distinguish CSS pixels from screen dots, then choose units for text, boxes and full-height sections. A container that can shrink and text that respects the reader’s settings give later layout changes a reliable base.
1.1 One page, many screen widths
Responsive design lets one HTML page adapt as its available space changes. A phone held upright, a tablet turned sideways and a resized desktop window should all show readable text, usable controls and images that fit. You design for a continuous range of widths, including the spaces between familiar device sizes.
Ethan Marcotte introduced the term in 2010 around three techniques: fluid layouts, flexible images and media queries. Flexbox, grid, container queries and responsive image markup now extend that toolkit. Each solves a different part of the job; a page needs more than a single setting.
Count the right pixels
A CSS pixel is a layout unit, not necessarily one dot on the screen. CSS defines 96px as equal to 1in; on a screen, that relationship does not promise a measured physical inch. A high-density screen uses several device pixels for each CSS pixel. The device pixel ratio describes that relationship.
A phone 390 CSS pixels wide with a ratio of 3 has 1170 device pixels across. A width query still sees 390px. The extra dots help draw sharp text and images; they do not give a layout three times as much space. This distinction matters when you later choose image files.
The viewport is the browser area used to display the page, excluding its own toolbars. Resizing a window or rotating a device changes the space available. On phones, showing and hiding toolbars can also change the visible height.
Tell mobile browsers the intended width
Mobile browsers can lay out an unconfigured page in a wide virtual viewport, commonly around 980 CSS pixels, then shrink it to the screen. On a 390px phone, the scale is about 0.4. Text declared at 16px then looks about 6.4px tall, and a narrow-width query may never match because the layout viewport is still wide.
Place this inside the document's <head>:
<meta name="viewport" content="width=device-width, initial-scale=1">
width=device-width asks for the device width in CSS pixels. initial-scale=1 starts at normal zoom. After adding it, reload the page in a phone-sized browser view and check both the text and the active width queries.
Keep zoom available. Do not add user-scalable=no or maximum-scale=1. Readers with low vision need to enlarge content; text must support enlargement to 200% without losing content or function. Some mobile browsers ignore zoom restrictions, but the page should support zoom itself.
Check the layout as well
The viewport tag does not change a fixed-width box. A .page with width: 960px still extends beyond a 390px viewport. Change rigid widths into fluid widths with limits, make media flexible and add layout changes where the content needs them.
To diagnose a tiny mobile page, first inspect the <head> for the viewport tag. To diagnose a page that is normal-sized but scrolls sideways, inspect the boxes that exceed the available width. These symptoms point to different causes.
Key Takeaways
- Responsive pages adapt across a continuous range of widths.
- Layout uses CSS pixels; device pixel ratio describes screen density.
- Put the viewport meta tag in the document head.
- Leave zoom enabled and make fixed-width content flexible.
1.2 Sizes that follow text and containers
Choose a unit by asking what the size should follow. A column usually follows its containing block. Button padding may follow the button's text. A paragraph's line length follows the font. Using the right reference makes changes work together.
| Unit | What it follows | Useful application |
|---|---|---|
% | A percentage width follows the containing block's width | Fluid boxes and columns |
em | Parent font size for font-size; own font size for other properties | Button padding and icons |
rem | Root element's font size | Text and shared spacing |
ch | Width of the font's "0" glyph | A readable line-length limit |
px | CSS reference pixels | A thin border |
Percentages and the box model
A box with width: 50% is 300px wide in a 600px containing block and 180px wide in a 360px one. Percentage padding and margins, including top and bottom values, also use the containing block's width in normal horizontal writing. Thus padding-top: 10% in a 600px-wide parent is 60px.
Height is different. A percentage height needs a definite reference height. When an ordinary parent's height comes from its content, height: 50% generally behaves as auto. Let text boxes grow with their content instead of using percentage heights to control them.
Use a fluid container with a maximum:
.page {
box-sizing: border-box;
width: 100%;
max-width: 70rem;
margin-inline: auto;
padding-inline: 1rem;
}
On a narrow screen, the box fills the available width, with padding inside it. On a wide screen, it stops at 70rem and the automatic inline margins center it. With a 16px root, its maximum outer width is 1120px. border-box includes padding and borders in the declared width; under content-box, 100% width plus padding would overflow. A fixed width: 70rem would also prevent shrinking.
For example, a 340px-wide border-box wrapper with 16px of padding on each side has 308px left for its content when there is no border. The declared width describes the outside of this box. If you switch the same declaration to content-box, the content alone is 340px and the outer width becomes 372px. Inspecting these separate widths in developer tools makes padding-related overflow easier to spot.
Let text settings carry through
Leave the root font size at the reader's default, or use a percentage such as 100%. At a 16px root, 1.5rem is 24px; at a 20px root, it is 30px. A fixed html { font-size: 16px; } prevents that default-font preference from carrying through to root-relative sizes.
For font-size, em uses the parent's font size. Nested lists each set to 1.2em therefore compound: 16px becomes 19.2px, then 23.04px. Use rem when all nesting levels should keep the same size.
In other properties, em uses the element's own font size. A button with padding: 0.5em 1em gains padding as its text grows. That keeps the spacing in proportion without a separate breakpoint.
For paragraphs, max-width: 65ch provides a useful reading limit. The unit measures the width of "0", so it does not count characters exactly in a proportional font. Roughly 45–75 characters per line is a common reading guideline; check the actual font and text in the browser.
Key Takeaways
- Percentages make widths follow their containing block.
- Use border-box to keep padding inside a declared width.
- rem follows the root font size without nested compounding.
- em can keep component spacing proportional to its own text.
- ch offers a font-based line-length limit.
1.3 Fluid sizes with useful limits
Viewport units follow the browser's viewport even when an element sits inside a smaller box. 1vw is 1% of the viewport width; 1vh is 1% of its height. vmin uses the smaller dimension, and vmax uses the larger. In an 800px-wide viewport, 50vw is 400px. In a 300px-tall viewport, 70vh is 210px.
This reference matters. A sidebar can be only 260px wide in a 1400px window. A child with width: 50vw asks for 700px, so it will not fit that sidebar. Use a percentage when the child should follow its parent. For an ordinary full-width block, prefer width: 100%: 100vw can include a desktop scrollbar's width and create sideways scrolling.
Choose which mobile height you mean
Mobile browser toolbars can reduce the visible page area. The viewport height units distinguish three states:
| Unit | Height it follows | Main tradeoff |
|---|---|---|
svh | Small viewport, with toolbars shown | Stable size that fits that state |
lvh | Large viewport, with toolbars hidden | May extend behind visible toolbars |
dvh | Current dynamic viewport | Can resize during scrolling |
Plain vh corresponds to the large viewport. Width variants such as svw, lvw and dvw also exist. For a tall opening section, min-height: 100svh sets a stable minimum while allowing longer content to grow. A fixed height leaves overflow to spill out when the content becomes taller. Dynamic units can follow toolbar changes, but updates may happen in steps and make the layout move.
Choose the height reference by the behavior you need. A stable opening section can use the small viewport even after the toolbars disappear; it does not have to stretch again just because more space becomes visible. A panel intended to follow that changing space can use dynamic units, accepting the possible movement. In either case, a minimum height lets additional content extend the section in normal flow.
Put bounds around a fluid value
min() selects the smaller value and can cap a width: width: min(100%, 40rem) fills the parent until it reaches 40rem. max() selects the larger value and provides a floor. clamp() gives a floor, a preferred value and a ceiling in that order.
.title {
font-size: clamp(1rem, 0.5rem + 2vw, 2rem);
}
With a 16px root, the floor is 16px, the preferred size is 8px plus 2% of the viewport width, and the ceiling is 32px. Work through the bounds:
- At 375px, the preferred size is 15.5px, so the 16px minimum applies.
- At 1000px, the preferred size is 28px, within the limits.
- At 1400px, the preferred size is 36px, so the 32px maximum applies.
The same functions accept calculations such as min(100% - 2rem, 70rem). Keep compatible length values and spaces around the subtraction operator.
Text sized only in vw can become tiny on narrow screens and huge on wide ones. Desktop zoom also narrows the viewport in CSS pixels, which can cancel that text's enlargement. Include a font-relative part and useful bounds, then test text enlargement: a mixed rem/vw expression alone does not guarantee a full 200% increase.
Key Takeaways
- Viewport units follow the window, even inside a narrow parent.
- Use svh for the small viewport and dvh for the changing visible height.
- min() caps a value; max() gives it a floor.
- clamp() sets a minimum, preferred value and maximum.
- Test fluid type with zoom as well as changing window widths.
2Adapt layouts with media queries
A layout needs to work while the window is changing, including between its major arrangements. Write conditions that apply CSS at the right time, start from a useful narrow page and add columns when the content has room. Flexbox and grid can handle many changes automatically; explicit breakpoints handle the moments when the arrangement itself needs to change.
2.1 Conditions that switch CSS rules
A media query applies CSS when a condition about the output, viewport or reader's preferences is true. The browser checks again when relevant conditions change, so resizing a window can switch styles without reloading the page.
.heading { font-size: 1.25rem; }
@media (min-width: 40em) {
.heading { font-size: 2rem; }
}
At the usual 16px browser default, 40em is 640px. The larger heading applies from that width upward. In media queries, em and rem use the browser's initial font size, not an author-set size on <html>. A reader with a 20px default gets the same switch at 800px.
Read conditions precisely
min-width includes its boundary: 600px matches min-width: 600px. max-width also includes its boundary. Range syntax makes the comparison explicit:
@media (width >= 600px) { /* wider layout */ }
@media (600px <= width < 900px) { /* middle band */ }
If you pair max-width: 600px with min-width: 600px, both match at 600px. Using 599px and 600px instead leaves a gap at fractional widths such as 599.5px. Increasing minimum-width queries avoid that gap; complementary ranges such as < 600px and >= 600px are another option.
Media types identify output: screen, print or the default all. @media print can remove navigation and use dark text on white paper. Conditions combine in useful ways:
| Form | Meaning |
|---|---|
screen and (min-width: 40em) | Both the output type and width must match |
(max-width: 30em), print | Either narrow output or printing matches |
not print | The output is not print |
only has no useful effect in current browsers. Width and height describe the viewport; orientation: portrait means its height is at least its width. Other features test input precision, hover, resolution, reduced motion and color scheme. A landscape viewport does not tell you whether the reader has a mouse.
For a practical condition, @media (hover: hover) and (pointer: fine) requires a primary input that can hover and target precisely. A narrow mouse-driven window can match it, while a wide touch-first device may not. Use the query for optional pointer effects; keep the underlying action available through the normal page controls.
Keep the cascade in view
A media query does not increase a selector's specificity. In a normal stylesheet with equally specific rules, the later matching declaration wins. If the base .heading rule appears after the wider-screen rule above, it wins at wide widths too. Put base rules first and the queries that change them afterward.
You can also attach a condition in HTML. <link rel="stylesheet" href="print.css" media="print"> applies its rules when printing, but a browser can still download the file at a lower priority. A <source> element's media attribute uses conditions to choose an image source.
Key Takeaways
- Media queries respond to output, viewport features and user preferences.
- min-width and max-width include their boundary values.
- and requires all conditions; a comma offers alternatives.
- Query rules still obey the normal cascade and specificity.
- Relative query units use the browser’s initial font size.
- Complementary ranges avoid fractional-width gaps.
2.2 Add layout as space becomes available
Mobile-first CSS starts with the narrow layout as ordinary rules outside any query. Minimum-width queries then add changes when space permits. This suits normal document flow: blocks already stack vertically, so the base page often needs little layout code.
Desktop-first CSS starts with wide-screen rules and uses maximum-width queries to undo them. Both approaches can work, but mobile-first usually makes the base and each later change easier to follow.
Build from one column
.cards {
display: grid;
gap: 1rem;
}
@media (min-width: 40em) {
.cards { grid-template-columns: 1fr 1fr; }
}
@media (min-width: 64em) {
.cards { grid-template-columns: repeat(3, 1fr); }
}
With a 16px default, the changes happen at 640px and 1024px. A 500px viewport shows one column. At 800px, the first query matches and gives two columns. At 1200px, both queries match; the later rule gives three columns.
The wider query does not turn the earlier query off. If you reverse their order, the 40em rule is last and reduces the wide layout to two columns. Keep increasing minimum-width queries in increasing order when they change the same property with the same specificity.
Find the breakpoint in the content
A breakpoint is where a query changes the layout. Start with the actual content in a narrow window, then widen it slowly. Look for navigation wrapping awkwardly, paragraphs becoming too long or cards stretching beyond a useful reading width. Add a change where it improves that content.
Do not choose a breakpoint just because a familiar device has that width. Screens vary, desktop windows can be any size, and a larger font can make the same navigation need more space. Relative-unit breakpoints can help the layout respond to the reader's default text size.
After each change, test both sides of the breakpoint and several widths between changes. A layout that looks right only at 375px, 768px and 1280px still has many opportunities to fail. Fluid widths, wrapping and automatic grid columns handle much of that in-between space.
Test the navigation and the card list together after adding a page sidebar. The window has become wider, but the main column may have become narrower because it now shares that space. A card layout that worked just below the page breakpoint can fail just above it. This is a useful place to let cards wrap or fit automatic columns while the page itself uses an explicit query.
Keep the content and downloads useful
Phone users need the page's content too. If a secondary explanation takes too much space, stack it lower or put it in a native <details> disclosure that readers can open. Do not remove necessary information just to make a narrow screenshot look tidy.
Starting narrow also helps you choose a light default page. Hiding a large image with CSS does not reliably prevent its download; use responsive image markup to offer suitable files. A readable single-column page with a smaller image is a strong starting point, then wider layouts add room and rearrange it.
Key Takeaways
- Write narrow-screen base rules outside queries.
- Add matching min-width changes in increasing order.
- Place breakpoints where the content needs a layout change.
- Test widths between breakpoints, including larger text.
- Reorganize useful content for phones and send suitable image files.
2.3 Responsive rows and columns
A layout can adapt through an explicit query or through its own sizing rules. Use a query when the arrangement must change at a chosen point. Use an intrinsic layout when items simply need to fit into the available space.
Let grid count the columns
.tiles {
display: grid;
grid-template-columns:
repeat(auto-fit, minmax(min(15rem, 100%), 1fr));
gap: 1rem;
}
At a 16px root, each column aims to be at least 240px. Grid fits as many as possible, subtracts the gaps, then shares the remaining width with 1fr. In a 1000px container, four 240px columns plus three 16px gaps would need 1008px, so only three fit. Each gets about 322.7px. A 700px container gets two 342px columns; a 360px container gets one.
The inner min(15rem, 100%) matters when the container is under 240px wide. It lets the minimum become the available width. Without it, the 240px minimum would force overflow. auto-fit collapses empty tracks, letting a few items expand; auto-fill keeps empty tracks and can leave those items narrower.
Let flex items wrap
.links {
display: flex;
flex-wrap: wrap;
gap: 1rem;
}
.links > * { flex: 1 1 15rem; }
Each item starts from a 15rem basis, can shrink or grow and wraps when the row cannot fit more items. Each line shares its own remaining space. Two items on the final line can therefore become wider than items above them. Grid is a better fit when column widths should line up across rows. Navigation can wrap too, or a query can switch its flex-direction to column.
Change the whole page when needed
Start the page in normal flow. Then add a sidebar arrangement:
@media (min-width: 48em) {
.page {
display: grid;
grid-template-columns: 16rem minmax(0, 1fr);
gap: 1rem;
}
}
At the usual 16px default, this starts at 768px. The first column is the sidebar; the second takes the remaining space. The zero minimum lets the main track shrink; its contents still need to wrap or scroll appropriately. Named grid areas can express a more complex arrangement.
Keep the HTML in a sensible reading order. Flex order and grid placement change where elements appear, but keyboard focus and screen readers still follow source order. Test by tabbing through links after rearranging them.
A wide data table may need its two-dimensional structure. Give it a local scrolling wrapper with overflow-x: auto, tabindex="0", role="region" and an accessible name such as aria-label="Event schedule". Only the table region should scroll sideways; the surrounding page should still reflow.
Key Takeaways
- Intrinsic layouts reflow without a breakpoint.
- auto-fit and minmax() fit columns and share spare space.
- Cap the column minimum at 100% to avoid narrow-container overflow.
- Flex lines share space independently; grid aligns columns across rows.
- Visual reordering does not change the HTML reading or tab order.
- Keep wide tables in a reachable, named scrolling region.
3Make components respond to their container
A component can appear in a wide main column or a narrow sidebar on the same page. Its own available width may matter more than the width of the window. Declare a measuring container, change the elements inside it and use container-relative sizes when they suit the component. Choosing the right reference keeps a reusable card useful wherever it is placed.
3.1 A card that follows its own space
A viewport-width query gives the same answer for every component on a page. That can be wrong for a reusable card: the window may be 1400px wide while the sidebar gives the card only 300px. A container size query measures an ancestor's available space, so the card can adapt to its actual slot.
Declare a wrapper, then style its contents
<div class="card-wrap">
<article class="card">...</article>
</div>
.card-wrap { container-type: inline-size; }
.card { display: grid; gap: 1rem; }
@container (min-width: 25rem) {
.card { grid-template-columns: 8rem minmax(0, 1fr); }
}
In horizontal writing, inline-size is width. It declares that the wrapper can answer inline-size queries. With a 16px root font, 25rem is 400px. A card in a 300px wrapper stays stacked; another in a 500px wrapper puts its image beside its text. Both can be on the same page at the same time.
A query measures an ancestor of the element being styled. If you put container-type only on .card and then try to change that same card, the query still looks above it. Use a wrapper as the measuring box and the inner card as the styled box.
Select the intended ancestor
An unnamed size query uses the nearest suitable ancestor size container. In a nested layout, that may be an inner wrapper. A name lets you choose a particular ancestor:
.panel { container: sidebar / inline-size; }
@container sidebar (width >= 30rem) {
.panel-title { font-size: 1.5rem; }
}
The shorthand sets both the name and type. If there is no suitable ancestor, the query does not match; the base styles continue to apply. Conditions can use ranges and logical operators such as and, or and not.
Make sure the container gets its size
Containment prevents the queried dimension from depending on the very contents that the query may restyle. Put container-type on a box whose width comes from the parent layout, such as a block, grid area or growing flex item. A shrink-to-fit box can collapse when its contents no longer contribute to its inline size.
container-type: size supports both width and height queries, but also contains block sizing. Its height needs an independent sizing arrangement; otherwise it can collapse. For ordinary cards, inline-size lets the height continue to follow the content. The default normal does not establish a size-query container.
Size features include width, height, inline size, block size, aspect ratio and orientation, provided the chosen container type supports the dimensions involved. Current major browsers support size queries. Keep a usable stacked base layout so the card still works if a browser ignores the enhancement.
Key Takeaways
- Put container-type on an ancestor wrapper.
- inline-size queries suit cards whose height should follow content.
- A container query styles descendants, not its own measuring box.
- Name a container when nested ancestors could change the intended reference.
- Give a query container a size through its surrounding layout.
3.2 Choose the size reference that fits the job
A responsive page can combine three approaches: automatic reflow, viewport conditions and component conditions. Decide what information the layout needs before choosing a query.
| Need | Useful tool | Reason |
|---|---|---|
| Fit repeated cards into a row | Intrinsic grid or wrapping flexbox | Items can reflow without a threshold rule |
| Change a page-wide sidebar arrangement | Media query | Available window space controls the page |
| Change a card in different page slots | Container query | The card needs its wrapper's size |
| Respect reduced motion or print output | Media query | These are user or output conditions |
Size within a container
Container query units describe percentages of a suitable ancestor container. cqw and cqh use width and height. cqi and cqb use inline and block size. cqmin and cqmax use the smaller and larger of the two dimensions. In horizontal writing, inline size is width.
In a 400px-wide eligible container, 5cqi is 20px. In a 600px-wide one, it is 30px. This lets a heading follow its own component, even when the whole page remains the same width.
Keep limits around text:
.card-wrap { container-type: inline-size; }
.card h2 {
font-size: clamp(1rem, 4cqi, 1.5rem);
}
With a 16px root, a 300px wrapper gives a preferred 12px, so the 16px minimum applies. At 600px, 4cqi is 24px, equal to the ceiling. Wider wrappers cannot push the heading above 24px. Test enlargement as well as wrapper resizing; fluid text must still remain usable when readers zoom.
Container units choose the nearest eligible ancestor for the direction measured. If none exists, they fall back to small viewport units. A forgotten container-type can therefore make text change with the window while appearing to work. Inspect the ancestors when a size seems to follow the wrong space. A container name on a query does not, by itself, retarget every container unit to that named ancestor.
Combine the tools
A page can switch to sidebar-and-main columns at 48em through a media query. Inside the main area, an automatic grid can fit as many cards as space allows. A card's own container query can move its image beside its text only when that particular slot is wide enough.
Do not replace a reduced-motion or hover query with a container query. A box's dimensions do not reveal a reader's preferences or input device. Likewise, copying a card's rules into separate viewport queries for every page slot ties that reusable component to each surrounding layout. Let its local space decide when its arrangement changes.
Key Takeaways
- Choose intrinsic reflow when no arrangement switch is needed.
- Media queries handle page-wide conditions and user preferences.
- Container queries handle a component’s available space.
- Container units use a suitable ancestor for each measured direction.
- Without an eligible container, container units fall back to small viewport units.
4Deliver images and media that fit every screen
Images need both a flexible display box and a sensible file to download. Preserve their shape, reserve loading space and decide when cropping is acceptable. Then describe alternative resolutions, crops and formats so the browser can choose from them. Matching image markup to the CSS layout keeps a page clear on dense screens without unnecessary downloads.
4.1 Flexible media without distortion
An image can be wider than the space the layout gives it. Start with a rule that lets it shrink while preserving its shape:
img, video {
max-width: 100%;
height: auto;
}
max-width limits the displayed width to the container without forcing a small image to fill it. width: 100% would stretch a small logo to the full width. Automatic height preserves the aspect ratio as the width changes.
Reserve the space before download
Keep dimension attributes in the HTML:
<img src="coast.jpg" width="1200" height="800"
alt="A rocky coast with a walking path">
Those dimensions give a 3:2 aspect ratio, so the browser can reserve space before the file arrives. When CSS displays the image 360px wide, the matching height is 240px. Removing the attributes because the image is responsive loses that early sizing information. CSS can still make the displayed image smaller than the attribute dimensions.
For an embedded video player, give the box its own ratio:
iframe {
width: 100%;
height: auto;
aspect-ratio: 16 / 9;
}
This keeps a 16:9 player shape while its width changes. Keep heights content-driven for text; a fixed aspect ratio is useful for media boxes with a known shape.
Choose whether cropping is allowed
A card thumbnail often has to fill a uniform box. Give it a width and an aspect ratio, then choose how the source fits:
.thumbnail {
width: 100%;
aspect-ratio: 4 / 3;
object-fit: cover;
object-position: top;
}
cover fills the box and crops parts that extend outside it. contain shows the whole image and can leave empty bands. The default fill stretches the image to the box, which can distort it. object-position chooses the alignment used when fitting; top alignment keeps the top portion visible in this example.
| Goal | Setting |
|---|---|
| Show an entire diagram | object-fit: contain |
| Fill a thumbnail box, accepting a crop | object-fit: cover |
| Preserve the natural shape while shrinking | height: auto with a width limit |
For a concrete comparison, place a 400 × 200 photo in a 320 × 240 thumbnail. Cover scales it to 480 × 240, then crops 160px of the scaled width in total. Contain scales it to 320 × 160, leaving 80px of unused height in total. Both preserve the source proportions; the choice is whether the box must be filled or the whole picture must stay visible.
Content images belong in <img> with useful alternative text. CSS backgrounds suit decoration; background-size: cover can crop them to fill their box, and media queries can switch the background file.
For images below the opening screen, loading="lazy" can defer fetching until the reader approaches them. Leave the main opening image eager so it can appear promptly. Shrinking a 4000-pixel photo with CSS still downloads that photo; responsive image markup is needed to choose a smaller file.
Key Takeaways
- Limit media width and preserve its aspect ratio.
- Keep width and height attributes to reserve loading space.
- cover crops; contain keeps the whole image visible.
- Use img for content and CSS backgrounds for decoration.
- Lazy-load lower images, not the main opening image.
- CSS display size does not reduce the downloaded file.
4.2 Offer the right image resolution
One photo can have several files with the same content and proportions but different pixel dimensions. Resolution switching lets the browser choose a file using the display size, screen density and its loading decisions. It saves unnecessary data while keeping enough detail.
Fixed display size: density descriptors
<img src="logo-200.png"
srcset="logo-200.png 1x, logo-400.png 2x"
width="200" height="80" alt="Northwind Books">
The logo is displayed 200 CSS pixels wide. The 200-pixel file suits a ratio-1 screen; the 400-pixel file supplies two source pixels per displayed CSS pixel for ratio 2. This form uses x descriptors and needs no sizes attribute.
Changing display size: width descriptors
<img src="park-800.jpg"
srcset="park-480.jpg 480w,
park-800.jpg 800w,
park-1600.jpg 1600w"
sizes="(min-width: 64em) 50vw, 100vw"
width="1600" height="1000"
alt="Trees around a park pond">
Each w value must state the file's real pixel width. It does not set a CSS width. The CSS still controls the box, and sizes describes that intended display width to the browser.
The first matching condition in sizes wins. With a 16px browser default, at 1024px or wider the slot is 50vw; below that it is 100vw. The final unconditional length is the fallback. Lengths can use viewport units, pixel or font units, and calculations such as calc(100vw - 2rem), but not percentages. When sizes is absent with width descriptors, the browser normally assumes 100vw.
Work out the needed detail
Multiply the described display width by the device pixel ratio. For a smallest-sufficient selection, compare that target with the supplied file widths:
- A 1200px viewport at ratio 1 uses the 50vw slot: 600 CSS pixels. The 800w file is the first large enough.
- A 390px viewport at ratio 3 uses 390 CSS pixels. It needs 1170 source pixels, so 1600w meets the target.
- The same narrow viewport at ratio 2 needs 780 source pixels, which 800w meets.
Real browsers can reuse a cached larger file or favor a smaller one under constrained loading conditions. The markup supplies candidates and sizing information, not an unconditional command to fetch one exact file.
Browsers begin fetching images before full CSS layout is available. That is why the sizing hint belongs in HTML. If the CSS gives an image half the viewport but sizes says 100vw, the browser may fetch too large a file. Update sizes when the layout changes. Keep src as a fallback and use a single alt text. Different crops need <picture>, because ordinary resolution candidates should remain interchangeable views of the same image.
Key Takeaways
- Use x descriptors for a fixed display size and different densities.
- Use w descriptors for file widths and sizes for the intended slot.
- The first matching sizes condition wins; percentages are not slot lengths.
- Estimate source width from display width and device pixel ratio.
- Keep sizes consistent with CSS; the browser retains selection freedom.
4.3 Choose a crop or image format
Reducing a photo's pixel dimensions keeps the same composition. Sometimes a phone needs a different composition: a wide stage photo can make the speaker too small to recognize. Art direction changes the crop or image so its important subject remains clear.
The <picture> element supplies ordered source choices, followed by a required <img>:
<picture>
<source media="(min-width: 50em)"
srcset="stage-wide.jpg" width="1600" height="900">
<img src="stage-close.jpg" width="800" height="1000"
alt="A speaker presenting on stage">
</picture>
With a 16px default, the wide crop is selected from 800px upward; below that, the image uses the closer crop. The <img> remains the displayed element. It supplies fallback behavior and the alternative text, and it is the element your image CSS styles. A <picture> without <img> displays no image.
Put the strongest conditions first
The browser chooses the first supported source whose conditions match. Suppose you offer crops at 30em and 60em. List the 60em minimum first, then 30em, then the fallback. If 30em is first, it also matches a very wide screen and prevents the browser reaching 60em. Non-overlapping ranges can also make the intended choice clear.
A source's media condition is a selection instruction. By comparison, ordinary srcset candidates and sizes give the browser information to choose an appropriate resolution. Use art direction when the composition needs to change; use resolution switching when the image content stays the same.
Offer formats in preference order
<picture>
<source type="image/avif" srcset="hall.avif">
<source type="image/webp" srcset="hall.webp">
<img src="hall.jpg" width="1200" height="800"
alt="Rows of seats in a lecture hall">
</picture>
A browser that supports the first format can use it; otherwise it tries the next supported choice and ultimately the JPEG fallback. AVIF and WebP often provide smaller files at comparable visual quality. The type attribute lets the browser skip unsupported formats without downloading them to find out.
Each source can also offer several width candidates with its own srcset and sizes. That combines a chosen crop or format with resolution switching. When art-directed crops have different proportions, dimension attributes on the sources let the browser reserve the appropriate space for each crop.
Write the alternative text once, on <img>, and make sure it describes every crop. If a close crop removes a second person, an alt description naming two people no longer fits. For a purely decorative image, use alt="" so it does not add unnecessary spoken content.
Key Takeaways
- picture needs an img for display, fallback and alt text.
- Use art direction when the composition changes.
- The first supported matching source wins, so source order matters.
- A source type can offer a preferred format with fallback.
- Every crop must agree with the one alt description.
5Test and refine responsive pages
A page can look correct in one screenshot and still fail with a longer title, larger text or a different input device. Test its widths and zoom levels, trace boxes that overflow and inspect the images it downloads. Touch targets, motion preferences, color themes and print output complete the checks that make the same content usable in different conditions.
5.1 Find the width where the page fails
A responsive page needs testing across a range, not just at a few named devices. Open the browser's responsive view, set a narrow viewport near 320px and drag toward a wide window. Watch headings, navigation, cards and image edges as you move. Test immediately below, at and above each breakpoint.
Developer tools can emulate viewport dimensions, device pixel ratio and touch input. Chrome and Edge provide a device toolbar; Firefox and Safari provide responsive design modes. Emulation is useful, but real devices can differ in toolbar behavior, touch, fonts and performance. Check a real phone and tablet in both orientations, plus a resized desktop window.
Check reflow and enlarged text
WCAG's AA reflow criterion asks that ordinary content work at a width of 320 CSS pixels without requiring scrolling in two directions. A 1280px-wide viewport zoomed to 400% provides that width. Set a 320px responsive viewport for a direct narrow-width check, and also test actual desktop zoom to see how the page enlarges.
Content that needs a two-dimensional layout, such as a data table, map or diagram, can retain that arrangement. Keep any necessary sideways scrolling inside its own region. Surrounding headings, instructions and paragraphs should still fit the page width.
Use realistic content: a long title, an unbroken URL, many links and longer translated text. Raise the browser's default font size too. A box that looked roomy with a short sample may overflow when text grows.
Trace horizontal overflow
A sideways scrollbar or an empty strip at the right often means one box exceeds the viewport. Inspect suspicious elements and compare their box edges with the page boundary. Temporarily outline them:
* { outline: 1px solid red; }
An outline shows the boxes without adding to their measured width. Look for fixed widths, 100vw blocks, images without a width limit, wide minimum grid tracks, negative margins, long text and code blocks.
Match the fix to the cause:
| Cause | Useful repair |
|---|---|
| Rigid content width | Use a flexible width with max-width or min() |
| Oversized image | Limit width and use automatic height |
| Long unbroken URL | Use overflow-wrap: anywhere |
| A code block or necessary wide table | Add local overflow-x: auto |
| A grid track with an excessive minimum | Allow a smaller track minimum |
Do not hide the whole page's horizontal overflow as a shortcut. body { overflow-x: hidden; } can make the scrollbar disappear while leaving content beyond the reader's reach.
For a local scrolling table, test the interaction as well as the width. Use the keyboard to reach the named wrapper and check that its horizontal scroll reveals every column. Then continue tabbing to the next control. The table can require sideways movement without forcing the paragraph above it or the rest of the page into the same wide scrolling area.
Finally inspect image requests in the Network panel. Set both a phone-sized viewport and a realistic high device pixel ratio, reload under the intended test conditions and check the selected candidate and file size. A visually small image can still be a large download if its sizes hint is wrong.
Key Takeaways
- Sweep through widths and test breakpoint boundaries.
- Check reflow at 320 CSS pixels and actual zoom behavior.
- Use real devices to check behaviors emulation approximates.
- Inspect overflowing boxes and repair the specific cause.
- Check realistic content and the files images actually download.
5.2 Keep pages usable with touch and reader settings
Width is only one part of responsive behavior. A wide tablet can use touch; a narrow desktop window can use a mouse. Pages also need to work with zoom, larger text, different orientations and the reader's preferred motion and color settings.
Make controls easy to reach
WCAG 2.2 AA target-size guidance calls for at least 24 × 24 CSS pixels or sufficient separation under its spacing rule, with exceptions such as links within sentences. The AAA size criterion uses 44 × 44 CSS pixels, also with exceptions. Larger padded navigation links are often more comfortable than a dense row of tiny labels.
At a 16px root, a link with 16px text, line-height: 1.5 and padding: 0.75rem 1rem has a 24px line box plus 12px above and below: 48px tall. Make the link itself the padded clickable box.
Essential information must not depend on hover. Keep actions visible or reachable by tap and keyboard focus. Add optional hover effects only when the main input supports them:
@media (hover: hover) and (pointer: fine) {
.card:hover { outline: 2px solid currentColor; }
}
pointer: coarse describes an imprecise primary input such as a finger. any-pointer and any-hover check whether any connected input has a capability; they do not establish that every reader is using it.
Let enlarged text and rotation work
Keep zoom enabled and verify text enlargement to 200% without lost content or function. Use font-relative sizes and growing text boxes. min-height lets a box grow when its content grows; fixed height can let enlarged text spill into the next section.
Support portrait and landscape unless one orientation is essential to the activity. Landscape phones can have very little vertical space. A height query such as @media (max-height: 30em) can let a sticky header scroll away so it does not cover the content.
Respect preferences and output
Use prefers-reduced-motion to avoid large motion for readers who request less. One approach is to put optional animations inside @media (prefers-reduced-motion: no-preference). You can also remove an existing animation inside a reduce query.
For a dark theme, pair readable text and background colors inside @media (prefers-color-scheme: dark). Check contrast in both themes. color-scheme: light dark lets browser-drawn controls and scrollbars follow an appropriate theme; it does not choose all of your page colors for you.
A reduced-motion rule can target only the animated component:
@media (prefers-reduced-motion: reduce) {
.banner { animation: none; }
}
Keep the message itself available when movement is removed. For a dark theme, change foreground and background together; changing only one can make text blend into its surroundings. Preview form controls too, since browser-drawn controls can differ from your authored surfaces.
Use @media print to hide navigation and buttons and produce dark text on white. Printed links can show their destinations with a[href]::after { content: " (" attr(href) ")"; }. Test a print preview to check that content, backgrounds and page breaks remain readable.
Key Takeaways
- Size the clickable target, including its padding.
- Use input features to check hover and pointer precision.
- Keep essential content available to tap and keyboard users.
- Support zoom, growing text boxes and both orientations.
- Respect reduced motion and test both color themes.
- Provide readable print styles and useful link destinations.
Responsive Web Design examples
1Build a flexible event page
13 steps
- 1IntroductionBuild a flexible event page
An event page has tiny text on a phone and a content box that extends beyond the screen. Start by separating the browser’s layout width, set by the viewport, from the size of the boxes inside it. Then make the wrapper follow available space and choose text and height units with useful limits, such as clamp, so nothing breaks on narrow windows or enlarged text. You will check each change against a specific cause instead of changing several unrelated sizes at once.
- 2ExplanationRead the viewport in CSS pixels
A high-density display does not provide extra CSS layout width. If a phone has 1080 device pixels across at a device pixel ratio of 3, the corresponding width is 360 CSS pixels. A media query and a viewport-width unit use that CSS width. The physical dots provide finer detail for drawing text and images; they do not turn a narrow page into a desktop layout.
- 3ExampleFix the wide virtual layout
The event page has no viewport instruction, so the mobile browser can lay it out in a wide virtual viewport and shrink the result. Put this in the document head:
<meta name="viewport" content="width=device-width, initial-scale=1">Reload the narrow preview. The page now uses the device width in CSS pixels and starts at normal scale. Leave zoom enabled for readers who need larger text.
- 4ChallengeExplain the remaining sideways scroll
After the viewport change, the text looks normal, but the event wrapper is still
width: 900pxon a 360px viewport. Why does it still scroll sideways?---reveal---
The tag changed the browser’s starting layout viewport, not the wrapper’s CSS width. A 900px box still exceeds 360px. Make the wrapper fluid with an upper limit so it can shrink to the space the page actually has.
- 5ExampleGive the wrapper room to shrink
Replace the wrapper’s fixed width with a full-width box and a cap:
.event { box-sizing: border-box; width: 100%; max-width: 68rem; padding-inline: 1rem; margin-inline: auto; }The wrapper follows a narrow parent but stops growing on a wide screen. Border-box includes the padding inside its declared width, while automatic inline margins center the capped box.
- 6ExplanationChoose a reference for text and spacing
Leave the root font at the reader’s default. A
1.25remlabel becomes 20px with a 16px root and 25px with a 20px root. For a button’s padding,emcan be more useful:padding: 0.5em 1emfollows the button’s own text size. In the font-size property itself, however, em follows the parent. That difference explains why nested em font rules can compound. - 7TipLimit paragraph width with the font
The event description should not stretch into one very long line on a wide screen. Add
max-width: 62chto its reading area. A ch measures the width of the font’s digit "0", so the result is a useful font-based limit, not a promise of exactly 62 characters per line. Check the real font and text; narrow windows will still make the paragraph wrap before it reaches that cap. - 8ChallengeKeep a button’s proportions
A button’s own font increases from 16px to 24px. Its horizontal padding is
0.75em. What happens to each side’s padding, and why?---reveal---
It increases from 12px to 18px because em in padding follows the button’s own font size. This lets the surrounding space grow with the label. A padding value in rem would instead follow the root font and would not necessarily change with this local font increase.
- 9ExplanationFit a tall opening section
The event’s opening section should fill a phone screen without trapping longer text in a fixed-height box. Use
min-height: 100svh. The small viewport represents the state with browser toolbars visible; min-height allows the section to grow beyond that starting size. Plain vh follows the large viewport, while dvh follows toolbar changes and can make the section resize during scrolling. - 10ExampleStart a bounded heading size
For the event title, try:
.event h1 { font-size: clamp(1.5rem, 1rem + 2vw, 2.5rem); }With a 16px root, the limits are 24px and 40px. In a 600px viewport, the preferred value is 16px plus 12px, giving 28px. Because 28px is inside the limits, the browser uses it. This produces a smooth change without a separate query for each size.
- 11ExampleApply the limits at both ends
Keep the same heading expression and 16px root. At 300px wide, the preferred value is 16px plus 6px, or 22px, so the 24px floor applies. At 1600px wide, it would be 48px, so the 40px ceiling applies. The middle expression suggests a size; clamp decides whether that suggestion falls inside the allowed range. It does not scale all three arguments together.
- 12ChallengeChoose units and check enlargement
The event page’s wrapper fits, but its title uses only
6vwand barely enlarges during desktop zoom. What should you change and then test?---reveal---
Use a font-relative contribution and sensible limits instead of pure viewport sizing, then test actual text enlargement. Zoom narrows the viewport in CSS pixels, reducing a vw-only font size. Even a mixed rem/vw expression needs a zoom check to confirm that readers can enlarge the text enough.
- 13RecapCheck the flexible base
Check three references before adding layout changes: the mobile viewport uses device width, the wrapper follows its parent, and text sizes respect a font reference. Bound fluid values where needed and let text boxes grow. Try a narrow window, a wide window and enlarged text before moving on to additional columns.
2Turn a card list into an adaptive layout
14 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTurn a card list into an adaptive layout
- 2ExplanationMake a width condition readable
- 3ExampleCombine conditions with the right meaning
- 4ChallengeFind a boundary gap
- 5ExampleWrite the narrow layout first
- 6ExampleAdd two columns when they fit
- 7ChallengeKeep the wider change in control
- 8ExplanationLet grid fit columns automatically
- 9ExampleCount tracks and gaps together
- 10Key InsightChoose how empty space behaves
- 11ChallengeKeep the narrow grid usable
- 12TipPreserve the reading order
- 13ChallengeCombine page and component behavior
- 14RecapCheck each transition
3Reuse one card in different page slots
10 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionReuse one card in different page slots
- 2ExampleCreate the measuring ancestor
- 3ExampleChange the card inside the wrapper
- 4ChallengeRepair a self-query
- 5TipName the intended measuring box
- 6ExplanationMake a local heading fluid
- 7ChallengeFind the surprising reference
- 8ConnectionKeep page and preference decisions separate
- 9ChallengeChoose conditions for a reusable card
- 10RecapInspect the reference box
4Deliver a clear image without a large download
15 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionDeliver a clear image without a large download
- 2ExampleKeep the photo inside its column
- 3ExplanationChoose what may be cropped
- 4ChallengeSeparate display size from file size
- 5ExampleOffer real file widths
- 6ExampleRead the slot before choosing a file
- 7TipKeep sizes and CSS together
- 8ChallengeChoose the needed resolution
- 9ConnectionUse density descriptors for the fixed logo
- 10ExplanationDecide whether the crop must change
- 11ExamplePlace the wide crop before the fallback
- 12ChallengeRepair crop ordering
- 13ExplanationOffer formats without changing the subject
- 14ChallengeFinish the workshop image plan
- 15RecapCheck the box and the request
5Test a page beyond its tidy preview
12 steps
Save this lesson to follow every Walkthrough step by step.
- 1IntroductionTest a page beyond its tidy preview
- 2ExampleSweep through the layout widths
- 3ExplanationCheck a zoomed reading width
- 4ExampleFind the box that crosses the edge
- 5ChallengeKeep a necessary wide region reachable
- 6ExampleMake the link itself large enough
- 7Key InsightDo not infer input from width
- 8ChallengeRepair a panel for enlarged text
- 9ExplanationTest motion, themes and print
- 10TipInspect downloads under the intended conditions
- 11ChallengePlan a final usability check
- 12RecapRepeat the condition that found the fault
Responsive Web Design practice questions
Set 1: Breakpoints, containers and usable controls10 Practice Questions
Question 1 of 10
Show answerHide answer
Question 2 of 10
Show answerHide answer
Question 3 of 10
repeat(auto-fit, minmax(14rem, 1fr)) with a 1rem gap. The root is 16px, there are many items, and the content width is 920px. How many columns fit?Show answerHide answer
Question 4 of 10
repeat(auto-fit, minmax(16rem, 1fr)). With a 16px root, the sidebar overflows and two main-area cards should stretch across their row. What track rule meets both needs?Show answerHide answer
Question 5 of 10
Show answerHide answer
Question 6 of 10
container-type: inline-size. Inside @container (width >= 24rem), .card changes to two columns, but it never changes. There is no eligible ancestor container, and the card is in a shrinking flex slot. What repair makes the query work reliably?Show answerHide answer
Question 7 of 10
5cqi inside an eligible 460px-wide container in horizontal writing. The viewport is 1380px wide. What is its computed font size before any other limits?Show answerHide answer
Question 8 of 10
max-width: 100%; height: auto. Its container is 450px wide. What displayed dimensions preserve its proportions?Show answerHide answer
Question 9 of 10
Show answerHide answer
Question 10 of 10
hover: none and pointer: coarse. How should a card’s essential details be provided?Show answerHide answer
Set 2: Viewport, sizing and layout foundations10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
width: 880px. What pair of changes addresses both causes?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
width: 60% in a containing block that is 450px wide. The panel has no padding or border. What is its width?Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
font-size: 1.25em, and has padding-inline: 0.8em. What is its horizontal padding on each side?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
clamp(1rem, 1rem + 1vw, 1.4rem)?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
(min-width: 760px) match?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
html { font-size: 12px; }. At what viewport width does (min-width: 36em) begin matching?Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
.items with equal specificity in the same layer. What appears at 70em?Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
flex: 1 1 14rem. Why can the final card be wider?Show answerHide answer
Save this lesson to see this answer.
Set 3: Image files, crops and display boxes10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
max-width: 100%; height: auto. What additional change addresses the download size?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
sizes="(min-width: 54em) 40vw, 100vw" and 600w, 1000w and 1800w candidates. At a 1000px viewport and ratio 2, assume the smallest candidate meeting the density target is chosen. Which file width results?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
sizes="100vw". What is the likely loading problem?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
sizes="(min-width: 38em) 100vw, (min-width: 66em) 45vw, 100vw". At 1152px and ratio 2, candidates are 640w, 1280w and 2560w. Under the smallest-sufficient selection rule, what happens?Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Set 4: Diagnose responsive pages across conditions10 Practice Questions
Save this lesson to see every answer and practice every set.
Question 1 of 10
width: 100% inside a 370px parent and has 20px left and right padding, with no border. What change makes the wrapper fit the parent while keeping that padding?Show answerHide answer
Save this lesson to see this answer.
Question 2 of 10
width: 30vw; height: 8rem. When text is enlarged, it overlaps the next panel. Which repair addresses both visible faults?Show answerHide answer
Save this lesson to see this answer.
Question 3 of 10
These rules are in one layer with equal specificity. What font size applies at a 900px viewport?
@media (min-width: 700px) { .title { font-size: 2rem; } }
.title { font-size: 1.2rem; }
Show answerHide answer
Save this lesson to see this answer.
Question 4 of 10
minmax(0, 1fr) main column. The main grid uses repeat(auto-fit, minmax(16rem, 1fr)), and a card URL measures 620px unwrapped, with overflow-wrap: normal. Which two edits let the main content fit without changing the sidebar?Show answerHide answer
Save this lesson to see this answer.
Question 5 of 10
panel contains a 280px inline-size container, which contains a card. Both ancestors are eligible. An unnamed 26rem query styles the card. What happens, and how can it deliberately use the outer width?Show answerHide answer
Save this lesson to see this answer.
Question 6 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 7 of 10
width: 100%; max-width: 48rem, with no padding, and the root is 16px. The image hint is sizes="50vw"; ratio is 2 and candidates are 800w, 1500w and 2000w. Under smallest-sufficient selection, what correction and file choice match the real slot?Show answerHide answer
Save this lesson to see this answer.
Question 8 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 9 of 10
Show answerHide answer
Save this lesson to see this answer.
Question 10 of 10
Show answerHide answer
Save this lesson to see this answer.
Stuck on your own question? Homework Help
Key Terms
A
Alternative text
alt description must remain accurate for every crop that the surrounding picture can select.Art direction
Aspect ratio
auto-fill
auto-fill leaves room reserved for additional empty tracks.auto-fit
auto-fit collapses the row's empty tracks.B
Border-box sizing
box-sizing: border-box so its side padding does not cause overflow.Breakpoint
C
Cascade
ch
65ch stays readable in a wide window without claiming an exact character count.clamp()
rem and vw in clamp() so it can grow with the window within useful limits.Color-scheme preference
contain
contain so all its labels stay visible even when its shape differs from the thumbnail.Container name
@container sidebar (width >= 30rem) looks for an eligible ancestor named sidebar.Container query unit
5cqi grows when its own card wrapper widens, even if the viewport stays unchanged.Container size query
Content-based breakpoint
cover
cover, so some content near its edges can disappear.cqb
cqi
4cqi gives a preferred font size of 20px.cqmin and cqmax
cqmin length follows the smaller reference dimension when the two dimensions differ.CSS pixel
D
Density descriptor
2x density descriptor.Desktop-first CSS
max-width query for smaller windows.Device pixel ratio
dvh
100dvh can resize while a phone's toolbar appears or disappears during scrolling.E
em
1em horizontal padding gains more space around its label when its own font grows.F
Flex wrapping
flex-wrap: wrap can form a second row instead of extending past the page.H
Horizontal overflow
Hover capability
I
Inline size
inline-size query responds to width while its height can still follow its text.Intrinsic image size
Intrinsic layout
L
Layout shift
Lazy loading
loading="lazy", while the main opening photo loads promptly.Logical operator
screen and (min-width: 40em) requires both screen output and a sufficiently wide viewport.lvh
100lvh can extend behind mobile toolbars while those toolbars are still visible.M
max()
max(1rem, 2vw) cannot become smaller than 1rem as the viewport narrows.Media query
min-width query adds a second content column when enough window space becomes available.Media type
@media print block removes navigation controls that a reader cannot use on paper.min-width condition
(min-width: 620px) is true at 620px and remains true at wider viewport widths.min()
width: min(100%, 36rem) fills narrow containers but stops growing at 36rem.minmax()
minmax(15rem, 1fr) cannot shrink below 15rem even if its container is narrower.Mobile-first CSS
min-width queries.N
Network panel
sizes hint that overstates the slot.O
Object fitting
object-fit: contain preserves every part of a diagram inside a uniform thumbnail box.object-position
object-position: top to keep the upper part of its source visible when cropped.Orientation feature
P
Percentage width
50% is 240px wide when its containing block provides 480px of width.picture
Pointer precision
pointer: coarse even when its viewport is wide.Print stylesheet
Q
Query container
container-type: inline-size can supply width information to a card inside it.R
Range syntax
(600px <= width < 900px) includes 600px but excludes 900px.Reduced-motion preference
prefers-reduced-motion: no-preference.Reflow
Relative unit
rem for text makes its size follow the root font instead of a fixed pixel value.rem
1.5rem is 30px before any zoom enlargement.Resolution switching
Responsive emulation
Responsive web design
S
Size containment
container-type: size box needs independent height sizing because its text no longer supplies that height.sizes
sizes="(min-width: 60em) 50vw, 100vw" describes a half-window slot on wider viewports.Small-viewport fallback
container-type can leave cqi sizing tied to the window instead of the card wrapper.source element
(min-width: 55em) can supply the wide crop before a narrow img fallback.Source order
srcset
480w, 800w and 1600w candidates that all show the same composition.svh
min-height: 100svh for a stable starting height while allowing content growth.T
Text enlargement
Touch target
V
Viewport
Viewport meta tag
<head> and requests width=device-width, initial-scale=1.Viewport unit
50vw still uses half the window width, even when that exceeds the sidebar.vw
10vw produces a computed length of 90px.W
Width descriptor
900w is correct only when the supplied candidate file is actually 900 pixels wide.- 1How the Web Works
- 2HTML
- 3HTML Forms
- 4CSS
- 5CSS Layout with Flexbox and Grid
- 6Responsive Web Design
- 7Building Accessible Web Pages
- 8Publishing a Website
About this lesson
Make your own Study Materials
Turn your notes, slides and documents into Study Guides, Practice Questions, Flashcards and 6 more tools.