Valid, Browser Specific CSS Properties

Everyone has had to use a hack or two to get their site to display the same in all the major browsers. 99% of the time Internet Explorer is screwing with something. The problem is, using “hacks” like * html .className makes your CSS invalid. Some people are bothered by this, others don’t care (as long as it works, its fine by me).

One solution is to parse the user agent with PHP and determine which browser the visitor is using. We can then format that information however we would like and apply the CSS tags to any element on our site. The easiest would be to add these custom tags to the tag and only have to reference it in one place.

An example selector could be body.IE-6 .content { height:200px; }, which would validate just fine.

Check out the PHP below to see how you can figure out which browser your visitors are using, or check out the demo page to see browser specific content.

The PHP

$ua = $_SERVER['HTTP_USER_AGENT'];

if(preg_match('/Version.*Safari/', $ua)) { //Safari
	$browser = 'SAFARI';
	preg_match('/Version\/([\d\.]*)/', $ua, $matches);
	$version = $matches[1];
} elseif(preg_match('/Chrome/', $ua)) { //Chrome
	$browser = 'CHROME';
	preg_match('/Chrome\/([\d\.]*)/', $ua, $matches);
	$version = $matches[1];
} elseif(preg_match('/Firefox/', $ua)) { //Firefox
	$browser = 'FF';
	preg_match('/Firefox\/([\d\.]*)/', $ua, $matches);
	$version = $matches[1];
} elseif(preg_match('/MSIE/', $ua)) { //Internet Explorer
	$browser = 'IE';
	preg_match('/MSIE\s([\d\.]*)/', $ua, $matches);
	$version = $matches[1];
}

The above will return which browser the user is using (out of Chrome, Firefox, Internet Explorer and Safari) and the major version number. You could update it to return the exact version number, but lets be honest here, 99.9% of the time we are going to be targeting IE6 and IE7.

What’s your thoughts on browser specific CSS? Don’t care about valid code? Use something similar?

View Demo

Leave a Comment

Please complete all required fields