Styling iPhones, iPads and desktop devices with CSS media queries sure has gotten easier recently. Gone are the days of multiple media queries to target hundreds of different devices and devices widths.
The rise of support for flex and other modern layout approaches has made things even easier. Here are three quick ways to keep your desktop and mobile CSS simple.
CSS Media Query for All Non-Touch Screen Devices
Touch screens do not support :hover, so we can use this target all devices that do support :hover, causing touch screen devices to ignore the styles within this @media query:
/* Style all devices that support :hover ------------------------------------------ */ @media (hover:hover) { /* put your desktop CSS here */ } /* End Desktop-Only Styles ------------------------------------------ */
CSS Media Query for All Touch Screen Devices
Touch screens do not support :hover, which we can use to target all touch screen devices without worrying about all the complicated devices sizes:
/* Style all touch screens ------------------------------------------ */ @media (hover:none) { /* put your mobile CSS here */ } /* End Mobile Styles ------------------------------------------ */
CSS Media Query for All Touch Screens, but Not iPads
iPads don’t support :hover, but they are large enough to inherit a lot the desktop’s styles, so we can modify the previous @media query so that it does not only apply to iPads.
/* Style all tablet touch screens ------------------------------------------ */ /* -- previously tried this without success @media not (device-width: 768px) and (hover:none)-- */ @media (hover:none) and (device-width: 768px) { /* put your iPad styles here */ } /* End all tablet touch screens ------------------------------------------ */
There are endless resources and conversations all over the internet about CSS media queries and all the ways to target devices. I couldn’t find what I was looking for today while working on a new small business website, so I wanted to share here to help anyone who can benefit.
There is more we can do with the media queries above, such as targeting the iPad in landscape or portrait orientation. If there is interest in such things via comments on this page, I will update the post.
No CSS post would be complete without a shoutout the the incredibly ingestible Chris Coyer and friends over at CSS Tricks. I pretty much have Chris’s blog on speed dial. Andrés Galante’s Touch Devices Should Not Be Judged By Their Size is the foundation of this post.