Sub topic 2
Combining Conditions with CSS Media Queries
Assume you know basic HTML, CSS selectors, the cascade, the box model, and units such as em and rem. This chapter uses that foundation to build layouts that respond to content and user needs.
Combining conditions with `and`, comma, and `not`
A media query tests a condition before applying CSS. The and operator requires every condition to match. A comma means “or,” so the styles apply when any query matches. The not operator reverses a query.
@media screen and (min-width: 30em) and (max-width: 60em) {
.sidebar {
display: none;
}
}
@media (prefers-color-scheme: dark), print {
body {
color: #222;
background: #fff;
}
}
@media not print {
.screen-only {
display: block;
}
}Use and for precise combinations. Use a comma when the same rule supports separate situations. Use not carefully because negated queries can be harder to read.
Mobile-first styling with `min-width`
Mobile-first CSS starts with the simplest layout. Larger screens add improvements with min-width queries.
.cards {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@media (min-width: 40em) {
.cards {
grid-template-columns: repeat(2, 1fr);
}
}
@media (min-width: 64em) {
.cards {
grid-template-columns: repeat(3, 1fr);
}
}Choosing breakpoints from content
A breakpoint is the width where the current layout stops working well. Resize the page and add a breakpoint when text becomes cramped, navigation wraps badly, or columns become too narrow. Do not choose breakpoints only because they match a particular phone or tablet.
flowchart TD
A[Start with one-column layout] --> B{Does content fit comfortably?}
B -- Yes --> C[Keep the current layout]
B -- No --> D[Add a content-based breakpoint]
D --> E[Increase columns or spacing]Fluid units and responsive layouts
Percentages size an element relative to its container. rem scales from the root font size. vw represents one percent of the viewport width. clamp() combines a minimum, preferred fluid value, and maximum.
.page {
width: min(92%, 70rem);
margin-inline: auto;
}
h1 {
font-size: clamp(1.8rem, 4vw + 1rem, 3.5rem);
}
.layout {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
@media (min-width: 48em) {
.layout {
grid-template-columns: 2fr 1fr;
}
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
}Grid is useful for rows and columns. Flexbox is useful for arranging items along one main direction. Both can remain fluid between breakpoints.
Exercise
Why is a content-based breakpoint usually better than a device-based breakpoint?
Show answer
It changes the layout when the content needs more space, so it works across more screen sizes and devices.