Exercise: Use media queries
A possible solution is at the end of this page.
Choose one of the programs from this course and change something about it when the screen is below or above a value. Here are a few ideas:
- Make an element disappear with
display: none;. - Change a custom property such as the font size:
--dwc-font-size: var(--dwc-font-size-xs);. - Completely change your CSS Grid layout.
The following example shows how a media query is structured. The chapter section on media queries has working examples if you get stuck.
@media (width < 600px) {
<CSS Selector> {
<CSS Styles>
}
}
Possible solution
The original course had no solution for this exercise, so this one was written for this book. It starts from Exercise-ConvertToCssLayoutComplete-Grid.bbj, the solution of the CSS grid exercise, and moves the grid into Exercise-MediaQueriesComplete.css, because a media query cannot override styles that a program sets directly on an element. Below 600px the form switches to one column, uses a smaller font and hides the optional Company field. The files are Exercise-MediaQueriesComplete.bbj and Exercise-MediaQueriesComplete.css, and you find all files in 10_AdvancedResponsive.zip.
/* Exercise-MediaQueriesComplete.css
* Layout for Exercise-MediaQueriesComplete.bbj: a two-column contact form
* that becomes a one-column form on narrow screens.
*/
.contact-form {
width: 100%;
height: 100%;
box-sizing: border-box;
display: grid;
grid-template-columns: auto 1fr;
align-items: center;
gap: var(--dwc-space-m);
padding: var(--dwc-space-l);
}
/* The Submit button spans every column, in both layouts */
.contact-form-submit {
grid-column: 1 / -1;
margin-top: var(--dwc-space-m);
}
/* The strict less-than keeps the two-column layout at exactly 600px */
@media (width < 600px) {
.contact-form {
grid-template-columns: 1fr;
gap: var(--dwc-space-s);
--dwc-font-size: var(--dwc-font-size-s);
}
.optional-field {
display: none;
}
}