Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sass: Dealing with the IE 4095 selectors per stylesheet restriction

Note: This question refers to a Rails project with Sass & Compass. Using the Rails Asset Pipeline? Then have a look at this question.

We are developing a big application with many use cases and many individually styled pages, partly for multiple contexts. Which simply means a lot of style information.

With the newest section of our application, we have broken Internet Explorer's limit of 4095 selectors per stylesheet. (Want a proof of this limitation? http://marc.baffl.co.uk/browser_bugs/css-selector-limit/)

Okay. So, why do we not simply split the application style sheet into multiple ones by design?

Well, mixins and selector inheritance will not work across multiple Sass files (not partials), right?

I'd say the quality of the stylesheets is rather good, we cannot optimize away the exceeding amount of selectors. (There is rather more to come.) I also believe that minimizing the amount of selectors should not be our primary optimization goal. The Sass core team advises to use selector inheritance instead of mixins where applicable in order to save CSS file size. By doing so, the number of selectors tends to grow though.

So what should I do?

I am thinking about writing a script that generates additional css files, partitioning my big application.css file. These would only be loaded in IE then (so that I don't have multiple requests in modern browsers). I would need a simple css parser for that in order to cut the application.css file after max. 4095 selectors at a valid position. And I would need an compass compile - after hook so that developers don't need to generate the IE files by hand in order to test it.

Please, tell me, that you got a better idea!

Best, Christian

like image 746
crispy Avatar asked Aug 05 '11 08:08

crispy


2 Answers

Mixins are usable across multiple files. However, it is logically not possible that @extend may work with multiple files. It is the purpose of this directive to result in a single rule (which should not be duplicated across multiple files). Therefore, I cannot split up files.

Thus, I implemented a splitter: https://gist.github.com/1131536

After these two commits have found their way into Sass and Compass, you can use the following hook in your Rails config/compass.rb in order to automatically create the additional stylesheets for IE:

on_stylesheet_saved do |filename|
  if File.exists?(filename)
    CssSplitter.split(filename)
  end
end

Update:

The CssSplitter mentionend above has been release as a gem: https://github.com/zweilove/css_splitter

like image 68
crispy Avatar answered Oct 12 '22 13:10

crispy


If you can't reduce the number of selectors, there is no choice other than to split the CSS file.

Your proposed solution for doing so already sounds optimal, if a little complicated to implement.

like image 20
thirtydot Avatar answered Oct 12 '22 11:10

thirtydot