Fewer Media Queries & User Agent Checks, Smarter CSS & JavaScript


CSS media queries are great to help adjust the overall styles of a web applications between different devices. With media queries, you can scope the styles based on screen size and have different layouts between desktop and mobile. Tablets like the iPad 3 and various Android devices have large enough screen sizes that it’s hard to scope certain styles to the device outside of the general layout. User agent sniffing is very clunky. Probing the browser for features is the best way to create the best web application user experience for different devices.

In order to use media queries, you need to make many assumptions about the visiting device’s screen size. Looking at the user agent in JavaScript requires endless amounts of if statements to handle the myriad of browsers. Using JavaScript, you can probe the device for functionality support. Knowing what the browser can handle allows you to build applications tailored to the browser.

Modernizr is a good tool to use for asking browsers for feature support, and even load supporting JavaScript for missing features. Once Modernizr is run, it probes your browser for feature support and puts css classes on the html element that show what the browser supports.  

What can I do with this?

Media queries and user agent sniffing can get you most of the way to the best experience, but it takes a lot of work. Knowing if the device has touch capability means that you can make buttons larger and remove unsupported hover states for phones and tablets. Other CSS gotchas you can check for are SVG support, css opacity and shadows, and fontface support. For JavaScript feature support, you can query the Modernizr object and perform proper handling of localstorage, animation support.

Does this fully replace media queries?

No. Media queries are still useful in layout changes for devices or windows as they increase and reduce in screen size. Using Modernizr feature “probing,” you are able to target your css (and certain JavaScript) to display differently per device.

Does this replace user agent checks?

Mostly. Unless there is a known bug in certain browsers, you can use the browser support coerced with Modernizr to verify and tailor user experience on each device. The only other use for keeping user agent checking would be submitting the information to an analytics system.