Return to Firewoiks

Extensions, resources & tutorials for Fireworks, Dreamweaver & HTML5 / CSS3 by UI developer, .

Layout Engine v0.5.1 - Browser Detection Done Right

Posted: February 18 2013

Feature detection using libraries such as Modernizr has (rightly) usurped browser sniffing as the method of choice for conditional styling and scripting. However, as Elijah Manor recently asked, Does Browser Sniffing Still Have a Place?, I firmly believe the answer is “yes”.

So, I've created Layout Engine, which is the best of both worlds by using feature detection to work out what “type” of browser is being used — including IE10!, which no longer supports conditional comments, and thus is not easily targeted without hacks.

Until recently, I've almost exclusively used the excellent CssUserAgent, to help with targeting things that feature detection alone cannot. However, since Opera has announced that it's changing it's rendering engine to WebKit, it's even clearer now that regular browser sniffing is not future proof.

I'll still use CssUserAgent for some things, however. In fact, when combining Layout Engine with CssUserAgent, you'll be able to identify the standard Android Browser (and its WebView variants), which unfortunately render <select>s as regular text inputs if either a border or background is applied in CSS.

How it works

  1. Layout Engine tests the support of various style features on the <html> element that are specific to a particular browser engine. If nothing matches, then it will return false.

    The following layout engines are detected: ie, khtml, mozilla, opera & webkit.

    The following versions are detected: ie- 7, 8, 9, 10 & opera- mini

  2. Up to 2 classes are applied to <html> with the syntax: .vendor-vendor_name and .vendor-vendor_name-version (optional)

  3. A JavaScript object with up to 2 properties is exposed: layoutEngine.vendor and layoutEngine.version (optional)

Usage

  1. Reference layout.engine.min.js in the <head> of your document
  2. In your CSS, use a vendor class to style elements appropriately, e.g.:
    .vendor-ie-10 {
    	line-height: 20px; /* 1px more than IE 8 */
    }
    
  3. If appropriate, in your JavaScript, use layoutEngine.vendor and layoutEngine.version to run conditional functions where relevant, e.g.:
    if (layoutEngine.vendor === 'ie' && layoutEngine.version === 10) {
        // Conditional script
    }
    

Caveats

IE 8, 9 and 10's Browser and Document Modes incorrectly detect IE 7 as IE 8. Real IE 7 works as intended, however.

IE 6 cannot be detected with Layout Engine. I recommend using IE Conditional Comments to target IE 6 and 7 instead.

What now?