Grow your CSS skills. Land your dream job.

Last updated on:

Add Data Attribute of User Agent

var b = document.documentElement;
b.className = b.className.replace('no-js','js');
b.setAttribute("data-useragent",  navigator.userAgent);
b.setAttribute("data-platform", navigator.platform );

Which results in data attributes being added to the html element like:

<html 
	data-useragent="Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)"
	data-platform="Win32">
	...

Which allows you to be able to target very specific browsers on very specific platforms with CSS:

html[data-useragent*="Chrome/13.0"][data-platform="Win32"] {
  ...
}

Reference URL

Comments

  1. Conor Haining
    Permalink to comment#

    This one is very useful!

  2. Damn, that is helpfull. And it’s a hell lot better SEO than the IE specific if statements in your HTML markup. The only thing you need to keep in mind is that this will only work on CSS that gets loaded after that specific bit of JavaScript runs. It’s also not completely bulletproof, since there’s no solid fallback or browsers that don’t support data attributes, although you might be forcing them on the elements this way, even in older browsers.

    What Googlebot should see when he looks at this page:

    <html>
        ...
    

    What your CSS gets to see is the same as Chris shows above.

  3. WTF. Don’t use user-agent sniffing when feature testing can be used instead.

    • Read Rogie’s article at the Reference URL. Feature testing, while obviously better, wouldn’t have helped him there.

  4. Permalink to comment#

    It is really very useful. Is that CSS will work in all browsers?

  5. Eric
    Permalink to comment#

    Will not work in IE6. I asked the folks at HTMLDoctor about styling data-elements.

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".