Optimize for Many, not all: Target only specific browsers when using CSS3 mixins with Compass

This is Part 2 of my 5 part series: “From good to Great, 5 Things you didn’t know Compass could do.”

CSS3 and HTML5 are fantastic technologies, and thanks to Compass we can start to utilize some of CSS3’s awesomeness in our stylesheets, without having to worry about exactly how every CSS3 compliant browser implements every method. If we want to use a CSS3 box-shadow style on a div, compass provides us with all the CSS necessary to do this, even though all browsers don’t implement it identically:

@import compass/css3/box-shadow

#my-div
  +box-shadow(#fff, 0px, 1px 0px)

produces this CSS:

#my-div {
  -moz-box-shadow: white 0px 1px 0px 5px;
  -webkit-box-shadow: white 0px 1px 0px 5px;
  -o-box-shadow: white 0px 1px 0px 5px;
  box-shadow: white 0px 1px 0px 5px;
}

This is part of the awesome that is Compass, it takes care of all the variations of the CSS3 declarations for each browser, as needed. However, if you are using a lot of CSS3 mixins, you may end up wit more CSS than you really want or need for your intended audience. For example, perhaps your site gets a majority of its traffic from Firefox, Chrome, and Safari web browsers, and traffic from opera, Konqueror/KHTML is fairly low. While its fantastic that Compass is taking care of all of the browser inconsistencies for you, you’ve got all the extra CSS laying around to support them, even though they make up less than 8% of your total visits.

If you are in a situation like this, fear not! Compass gives you the ability to slim down your CSS3 mixins, by explicitly disabling specific css3 browser support, right in your stylesheet!

All we have to do is add this at the top of our stylesheets:

$experimental-support-for-opera: false
$experimental-support-for-khtml: false

@import compass/css3/box-shadow

#my-div
  +box-shadow(#fff, 0px, 1px 0px)

and that will remove all css3 support from the Compass mixins for KHTML and Opera. This may feel like a strange optimization, but I think its definitely a useful one to know, especially if your traffic patterns make this decision easy for you. Some may think this is a micro-optimization, but it really depends on how heavily you are using the CSS3 mixins.