How to detect screen width in CSS

- by

CSS-LogoHave you ever wondered how a website can look great on your desktop and appear reformatted on your phone? The secret sauce is done via CSS Media Queries.

In a nutshell you define your styles for larger screens, and then override those styles with more mobile friendly options if the screen is smaller. You can specify the exact width which allows even to detect if someone is holding their device portrait or landscape.

Let’s look at how this can be accomplished with CSS rules.

CSS Rules: iPhone & Co.

iPhone screens are 320 pixels wide. At the bottom of your stylesheet, define this:

/* detect iPhone portrait */
@media screen and (max-width: 320px) {
    /* mobile styles go here */

Change the max-width value to something bigger to detect wider screens (iPhone landscape would be 480). Will also work on other mobile devices whose screen is 320 or narrower.

The media query will execute any CSS inside the curly braces. Usually you want to detect the “medium size” between phone and desktop – which is of course your tablet.

CSS Rules: iPad & Co.

An iPad screen is 768 pixels in portrait mode, and 1024 in landscape mode. Let’s detect the portrait size and make sure we execute CSS if the screen is wider than 320 (see above), but narrower than 768. Here’s how:

@media screen and (min-width: 321px) and (max-width: 768px) {
    /* tablet styles go here */

Ingenious, huh? If it’s one pixel wider than 320 and maximum 768, execute these styles. If it’s any wider than 768 the standard styles will be executed.

There’s just one more thing we need to do via HTML for all of this to work:

HTML Meta Tag for Retina Devices

Retina devices have a higher pixel density per inch, but they still work in pixel sizes. We need to tell those devices not to map “web pixels” to “retina screen pixels” by giving them a meta tag. This needs to go somewhere inside the HEAD of your HTML document (in WordPress, this is created in header.php):

<meta name="viewport" content="initial-scale=1.0" />

That should do the trick! Have fun creating responsively πŸ˜‰

If you enjoy my content, please consider supporting me on Ko-fi. In return you can browse this whole site without any pesky ads! More details here.

Leave a Comment!

This site uses Akismet to reduce spam. Learn how your comment data is processed.