Using Custom Properties and Media Queries in CSS

We can also use custom properties with media queries. For example, you can use custom properties to define light and dark color schemes:

:root {

–background-primary: hsl(34, 78%, 91%);

–text-primary: hsl(25, 76%, 10%);

–button-primary-bg: hsl(214, 77%, 10%);

–button-primary-fg: hsl(214, 77%, 98%);

}

@media screen and ( prefers-color-scheme: dark ) {

:root {

–background-primary: hsl(25, 76%, 10%);

–text-primary: hsl(34, 78%, 91%);

–button-primary-bg: hsl(214, 77%, 98%);

–button-primary-fg: hsl(214, 77%, 10%);

}

}

Similarly, we can use custom properties to change the base font size for screen versus print:

:root {

–base-font-size: 10px;

}

@media print {

:root {

–base-font-size: 10pt;

}

}

html {

font: var(–base-font-size) / 1.5 sans-serif;

}

body {

font-size: 1.6rem;

}

In this case, we’re using media-appropriate units for print and screen. For both media, we’ll use a base font size of 10 units—pixels for screen, points for print. We’ll also use the value of –­base-font-size: to set a starting size for our root element ( htmL ). We can then use rem units to size our typography relative to the base font size.

Custom properties can help us write simpler, more maintainable CSS.

Source: Brown Tiffany B (2021), CSS , SitePoint; 3rd edition.

Leave a Reply

Your email address will not be published. Required fields are marked *