Advantage to multiple CSS files


#1

I know that all of my app’s CSS files get merged together into a bundle and that the bundle gets loaded before any CSS files specified in the header (I also based on discussions with MDG that this may optionally be changing in 1.6 or later).

For some reason long forgotten I have my CSS split into files matching the HTML file’s name (in other words, I have foo.html, foo.css, bar.html, and bar.css). This might have made sense at one point when the CSS selectors in each file were only used in the matching HTML file, but that ship has sailed. Selectors are used in multiple HTML files and it has become hard to find the appropriate CSS file to modify.

Is there any advantage to having multiple CSS rather than a single one? Assuming that the single CSS file doesn’t become huge? Selector ordering would be easier in a single file, rather than having to worry about the order that the files get bundled.

I’m looking at moving to Stylus for my CSS so I’m going to be editing every file anyway so the work of combining them into a single (or just a couple) of files isn’t an issue. I’m just wondering if there is something about multiple CSS files that I’m missing (I’m still a relative newbie at CSS). Thanks for any advice, comments, or opinions.


#2

The key advantage of CSS in separate files is usually for maintenance, and organising related things together. The same reasons you don’t have just one big .js file with all the code in.

One benefit of separate CSS files is that you can import just the bits you need for a given build, thereby potentially reducing the overall size.

Some view frameworks (e.g. Angular and Vue) allow per component CSS styles to be referenced from the component definition. Though, personally, I prefer to include both the template and styles in the component definition.

There is a consideration for separate non-component CSS files though. Depending how you write your CSS rules you might want to build on existing styles - CSS are order sensitive. Having said that, most people have some base CSS rules that arranged to come first (e.g. bootstrap) and then page/component specific CSS styles are pretty independent of each other.
If you have the separate CSS files (especially in the non-import directories) it can be a little tricky to ensure predictable ordering (there are rules, but they aren’t always obvious).

Finally, it is worth mentioning CSS conventions. These can help reduce the risk of unexpected interactions between rules in different files. You can devise your own, or use something like BEM (http://getbem.com/introduction/). The BEM page has some links to other conventions/methodologies.
Both Vue and Angular have ways of making component styles ‘scoped’ to a given component, which nicely avoids many of the issues with clashing styles.