CSS: User Agent Selectors [How to Hack a specific browser]

Codes

Here’s a brilliant code snippet when you want to ‘hack’ for a specific bug to a specific version of a specific browser (User Agent Selectors). And Rogie ain’t talking about hacks for older browsers as we know them, .. no, hacks to target those newer browsers using data-useragent to target a specific browser and data-platform to target a specific device.

The thing is, some of all the old hacks work just fine on older browsers: IE6/7 hacks. It’s harder to find hacks for the newer browsers because, yes, you guessed it, they typically are better — so less vulnerabilities, less hacks.Rogie King

There is some more information and examples in Rogie’s article, I just want to show some of his examples. So, wanna target IE9, code like this:

<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'>
    ...
</html>

Oh, but it gets more interesting. Now we can target iPads easily. How so?

<html 
    data-useragent='Mozilla/5.0(iPad; U; CPU iPhone OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B314 Safari/531.21.10'
    data-platform='iPad'>
    ...
</html>

Now, voila! You have an attribute. And guess what? you can use CSS attribute selectors to style something. Let’s look at a snippet of CSS to hack a specific CSS property for Chrome version 13.0

html[data-useragent*='Chrome/13.0'] 
    .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
    }

Using the *= wildcard attribute selector, you can now match any portion of the string, in this case to target the useragent of Chrome 13.0x. If you wanted to apply the fix only to Chrome 13.0x browsers on Windows, you’d simply use a rule like:

html[data-useragent*='Chrome/13.0'][data-platform='Win32']

Last, you may have noticed the “touch” class. Yup, you can use that class to target touch devices. For instance, let’s say you wanted to make an action appear on :hover in your application. You might have some CSS like this:

li .action{
    opacity:0;
    }
li:hover .action{ 
    opacity: 1;
    }

But, touch devices don’t have :hover. Using the boilerplate addon, with one line of CSS, you’ll be covered:

.touch li .action{
    opacity:1;
    }
More Info