🍔 Full Stack
CSS Media Queries for Responsive Web Apps

Last updated: August 10th, 2020

CSS media queries for responsive websites.

Web developers use CSS @media queries to make their website responsive, or support multiple screen dimensions. Media queries use screen width as input to boolean logic statements about min and max width. While it is not necessary to provide different @media queries per device, it is generally accepted as practice to provide a custom range for common device sizes, like phone, tablet, and desktop.

There are a number of gotchas when it comes to CSS @media queries my Gist addresses. For example, a developer often uses integer values to define min and max width for a website. In practice, a client browser window can potentially be any floating point value, which is why some client browsers round client browser window values up or down to the nearest integer pixel before displaying web content. This behavior is not universally accepted by client browsers, so we must take steps to ensure our CSS layouts are displayed when we expect.

/* Phone size */
@media only screen and (min-width: 320px) and (max-width: 767px) {
}
 
/* Tablet size */
@media only screen and (min-width: 768px) and (max-width: 1365px) {
}

The above will cause a flash of unstyled content when the client screen width is a fractional value between 767 and 768, since min-width and max-width are inclusive and the browser does not round this value for you in all cases.

The correct way to write CSS @media queries to apply styles for all supported layout dimensions and minimize the chance of flash of unstyled content is to use decimal values up to, but not including the min-width of the next breakpoint.

/* Phone size */
@media only screen and (min-width: 320px) and (max-width: 767.9999px) {
}
 
/* Tablet size */
@media only screen and (min-width: 768px) and (max-width: 1365.9999px) {
}

I hope this article helps explain how to use CSS @media queries to make your website responsive for 100% of the web. Please contact me by email or on Twitter if you have any questions or suggestions.