TimKnowsBest logotimknowsbestdot com

CSS @media queries for responsive websites.

Updated: 2 months ago

2 MIN READ

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.

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) {

}

The source code for this article can be found here.

I include screen dimension queries for SmartWatch, Phone, Tablet, and Desktop.

I hope this article helps explain how to use CSS @media queries to make your website responsive for 100% of the web. Please leave a comment on my Github Gist link if you have any questions or suggestions.