css

Cross browser opacity snippet in LESS

I’m relying on this CSS-Tricks snippet for cross-browser opacity of HTML elements. Since I’m using the CSS preprocessor LESS, I wanted to make the snipped a little more reusable, so I turned it into a parametric mixin:

.opacity(@val) {
    -ms-filter: %("progid:DXImageTransform.Microsoft.Alpha(Opacity=%a)", @val*100); // IE 8
    filter: e(%("alpha(opacity=%a)", @val*100)); // IE 5-7
    -moz-opacity: @val; // Netscape
    -khtml-opacity: @val; // Safari 1.x
    opacity: @val; // good browsers
}

And of course, this is how we use it:

div.transparent {
    .opacity(0.5);
}

…which generates the following CSS output:

div.transparent {
    -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";
    filter: alpha(opacity=50;
    -moz-opacity: 0.5;
    -khtml-opacity: 0.5;
    opacity: 0.5;
}