4,096 CSS Selector Limit in IE
Feb 2nd, 2014
A while back I ran into an issue that took far too long to debug. The project I currently work on is a large-scale single page application. I couldn’t figure out why certain areas of the application had a broken layout. The problem was clearly CSS related, but I could not track down the issue in our code. I finally decided to debug the issue by removing sections of our stylesheets. It didn’t click with me that this could be another pesky IE bug until I realized that I could remove a few CSS selectors from ANYWHERE in our code base and it would fix the broken layout (obviously causing problems elsewhere). Eventually, I started to Google the issue and see if anyone else was experiencing this issue in older versions of Internet Explorer, and sure enough there were some other developers out there that had run into the same issue.
Apparently, IE9 and below have a limit to the number of CSS selectors that you can include on a stylesheet. That limit is 4,096. I should mention that we use SCSS and our styles are separated out into multiple files that make sense with how we organize our codebase. However, we use Grunt as our front-end build tool and we run a task that concatenates all of our stylesheets and our application’s index file points to a single stylesheet that is created as a result of that task.
A few years ago this never would have been an issue, but with the ‘single-page application’ becoming more and more prominent in the current state of software development it shouldn’t come as a surprise that some quirky bugs might arise in some older browsers. This was just a really difficult one to track down because it wasn’t immediately apparent as to what the issue might be.
Now, you’re probably wondering what our solution to the problem was. Turns out that there is a Grunt module that allows you to run a task that ‘blesses’ your CSS after all of your stylesheets have been combined into a single file. If you aren’t familiar with ‘blessing’ your CSS, have a look at this http://blesscss.com/. That’ll allow you to manually split up your stylesheet into multiple styles using the command line. However, if you are using Grunt to build your UI, you could use this Grunt module (https://npmjs.org/package/grunt-bless) to run a task at the time you build and it is smart enough to know when you are getting close to the 4,096 selector limit in IE and will split your stylesheet into as many individual files as necessary to safely avoid that pesky limit.