Search code examples
cssmedia-queries

CSS media queries needed for optimizing for smaller screens?


I haven't had a lot of exposure to CSS media queries; I'm basically learning via experimentation. I am trying to optimize my website to look good on all devices. I want it to use a specific CSS file if the browser width is large (desktop device, including Retina displays), a different CSS file if it is a tablet (iPad or other, including Retina), and a different CSS file for small screens (iPhone or other, including Retina). My current setup is included below, and results from them.

<link rel="stylesheet" type="text/css" href="stylesheets/prevhome.css" /> <!--Desktop -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width : 1024px), screen and (-webkit-min-device-pixel-ratio: 2)" href="stylesheets/tablet.css" /> <!-- Tablet -->
<link rel="stylesheet" type="text/css" media="screen and (max-device-width: 640px), screen and (-webkit-min-device-pixel-ratio: 2)" href="stylesheets/phone.css" /> <!-- Phone -->

This works great on desktop computers, but the Retina display MacBook Pro uses the Phone CSS file rather than the Desktop one. The iPad displays the tablet optimized version great, but the Retina display iPad uses the Phone optimized CSS file. An iPhone displays the page great using the Phone CSS file, and the Retina display iPhone displays it great as well. I do not know how my site looks on other devices, since I only have Apple devices available to test with.

So, my CSS links are obviously set up incorrectly. How can I correctly set this up? I don't want to target any specific devices, aside from Retina displays. A Windows tablet should use the tablet CSS file, not just the iPad. Can this be done with 3 CSS links and 3 files, one for desktop (greater than 1024 px?), one for tablet (less than 1024 pixels), and one for phones (less than 640 px)? Or must I do those links, then additionally create a link for each Retina device, the rMBP, iPad, and iPhone? Or even create more than 3 CSS files?


Solution

  • You don't need to detect Retina displays, just detect device-width:

    <link rel="stylesheet" type="text/css" href="stylesheets/prevhome.css" /> <!--Desktop -->
    <link rel="stylesheet" type="text/css" media="screen and (device-width : 1024px)" href="stylesheets/tablet.css" /> <!-- Tablet -->
    <link rel="stylesheet" type="text/css" media="screen and (device-width: 640px)" href="stylesheets/phone.css" /> <!-- Phone -->
    

    For web performance reasons, all of this can be done with a single CSS file, with @media (...) { selector1 { property: value; } } at-media blocks of rules instead of conditional loading of 1 to 3 files.