Sub topic 3
Making Images and Components Adapt
Assume you know basic HTML, CSS selectors, the box model, and relative units such as rem and em.
Making images flexible
A responsive image must fit its containing block without losing its aspect ratio. Use max-width rather than a fixed width so small screens can shrink it:
img {
display: block;
max-width: 100%;
height: auto;
}This prevents an image from creating horizontal scrolling. For important images, also provide useful alternative text and consider responsive image sources with HTML srcset.
Range syntax for media queries
Media Queries Level 4 supports comparison operators. This expresses an inclusive width range more clearly than separate minimum and maximum conditions:
@media (400px <= width <= 700px) {
.banner {
padding: 0.5rem;
}
}Browser support varies by feature and version, so check your support requirements before replacing established syntax.
Respecting user preferences
Media queries can read preferences selected in the operating system or browser:
@media (prefers-color-scheme: dark) {
body {
background: #121212;
color: #eeeeee;
}
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation: none !important;
transition: none !important;
}
}Do not use motion to communicate information. Make sure dark colors maintain readable contrast.
Adapting to hover and pointer capabilities
Touch devices may not have hover, and some styluses are less precise than a mouse. Limit hover-only decoration to devices that support accurate hovering:
@media (hover: hover) and (pointer: fine) {
.button:hover {
background: #0a58ca;
}
}Never make essential information or controls available only on hover.
Print styles
A print query can remove navigation and use high-contrast colors:
@media print {
nav,
.ads {
display: none;
}
body {
color: #000;
background: #fff;
}
}When to use container queries
A media query responds to the viewport. A container query responds to a component's wrapper. Use one when the same card can appear in sidebars, grids, or full-width regions:
.card-wrapper {
container-type: inline-size;
}
@container (min-width: 30em) {
.card {
display: flex;
gap: 1rem;
}
}Testing and debugging
Use browser developer tools to resize the viewport, emulate preferences, inspect matched media rules, and test touch input. Check intermediate widths, not only common device presets. Then test with a real phone, keyboard navigation, print preview, and slow network conditions.
Exercise
Which query is better when a card changes layout according to the width of its grid cell?
Show answer
A container query, because it responds to the card's wrapper rather than the viewport.