Compiling and maintaining ie-specific stylesheets

2019-01-12 08:04发布

问题:

What is the common practice for maintaining IE workarounds in a separate CSS file? I'm talking about deeper issues that are impractical to work out by other means (such as including an alternative image url along with a base64-encoded embedded resource; boxsizing.htc workaround etc.) NB: I'm conservative when considering dataURI vs vanilla spriting, so there are only a few

Sometimes I have to resort to code similar to

.some-class-lets-say-datepicker {
  background-image: url(data:image/png;base64,/*encoded image*/);
  *background-image: url(../gfx/lets-say-datepicker-icon.png);
}

with the encoded image string being on average 100~300 chars. Given the code above, this causes some redundand traffic - for compliant browsers to download the redundand URL, and for IE7 to download the base64 stringon top of the separate image request. I find this overhead to be insignificant for both (and, after all, IE7 users have much bigger issues to be worried about :)

At the same time the following would (?) be a lot cleaner:

<!--[if !IE]> -->
  <link href="main.css" rel="stylesheet" />
<!-- <![endif]-->
<!--[if lt IE 8]>
  <link href="main_ie.css" rel="stylesheet"/>
<![endif]-->

but separate maintenance does not seem appealing at all. Closure-stylesheets offer conditionals, is there something similar for SASS/LESS or is there a different approach altogether that you'd recommend?

回答1:

Sass (version 3.2+) can do this fairly easily if you're ok with generating 2 different stylesheets.

Here's your mixins:

$ie-only: false !default;

@mixin hide-from-ie {
    if $ie-only != true {
        @content;
    }
}

@mixin show-only-ie {
    if $ie-only == true {
        @content;
    }
}

In your SCSS files:

.some-class-lets-say-datepicker {
    @include hide-from-ie {
        background-image: url(data:image/png;base64,/*encoded image*/);
    }

    @include show-only-ie {
        background-image: url(../gfx/lets-say-datepicker-icon.png);
    }
}

Make a separate IE-only file that imports your other SCSS files, but has this at the top:

$ie-only: true;

Use conditional comments to serve old IE versions the generated css file with $ie-only set to true, and every other browser gets the one generated with $ie-only set to the default false.

Inspiration for this technique was found here: http://jakearchibald.github.com/sass-ie/



回答2:

You can use JavaScript to add a class to the HTML based on the browser and other things - I find these really useful! This is the one I use http://rafael.adm.br/css_browser_selector



标签: css sass less