291

Is there any advantage to having a single monster .css file that contains style elements that will be used on almost every page?

I'm thinking that for ease of management, I'd like to pull out different types of CSS into a few files, and include every file in my main <link /> is that bad?

I'm thinking this is better

  1. positions.css
  2. buttons.css
  3. tables.css
  4. copy.css

vs.

  1. site.css

Have you seen any gotchas with doing it one way vs. the other?

Zoe
  • 27,060
  • 21
  • 118
  • 148
Nate
  • 30,286
  • 23
  • 113
  • 184
  • 2
    This is a REALLY old question, but facing the same problem I found the one that I think it's [the best solution](http://manas.tungare.name/software/css-compression-in-php/), in case someone else gets to this page. Multiple files that get compressed with PHP and sent through a single request. – Francisco Presencia Nov 01 '12 at 17:59
  • 4
    @FrankPresenciaFandos doing this is ok'ish for a low traffic site, but running this script over and over on high traffic sites seems a little off. If you use a build script, you can have the best of both worlds and still maintain a performant web server since it's not running the php script (ever). – Chase Florell Feb 21 '13 at 21:50
  • 2
    It would be run only every time the css is changed, and then you'd have to include the resulting css file. – Francisco Presencia Feb 22 '13 at 13:10

18 Answers18

154

This is a hard one to answer. Both options have their pros and cons in my opinion.

I personally don't love reading through a single HUGE CSS file, and maintaining it is very difficult. On the other hand, splitting it out causes extra http requests which could potentially slow things down.

My opinion would be one of two things.

1) If you know that your CSS will NEVER change once you've built it, I'd build multiple CSS files in the development stage (for readability), and then manually combine them before going live (to reduce http requests)

2) If you know that you're going to change your CSS once in a while, and need to keep it readable, I would build separate files and use code (providing you're using some sort of programming language) to combine them at runtime build time (runtime minification/combination is a resource pig).

With either option I would highly recommend caching on the client side in order to further reduce http requests.

EDIT:
I found this blog that shows how to combine CSS at runtime using nothing but code. Worth taking a look at (though I haven't tested it myself yet).

EDIT 2:
I've settled on using separate files in my design time, and a build process to minify and combine. This way I can have separate (manageable) css while I develop and a proper monolithic minified file at runtime. And I still have my static files and less system overhead because I'm not doing compression/minification at runtime.

note: for you shoppers out there, I highly suggest using bundler as part of your build process. Whether you're building from within your IDE, or from a build script, bundler can be executed on Windows via the included exe or can be run on any machine that is already running node.js.

Chase Florell
  • 46,378
  • 57
  • 186
  • 376
  • Besides fewer HTTP requests, is there any advantage to the single monolithic file? My css may change over time, but the number of users will be quite small, most accessing via high speed connections. So I think that the advantage of multiple files will be far greater than fewer http requests... – Nate Feb 25 '10 at 17:57
  • 1
    fewer HTTP requests IS the reason. retaining visitors is priority #1, so if your page loads slow, they are less likely to stay. If you have the ability to combine (I see you're using asp.net) then I would highly recommend doing it. It's the best of both worlds. – Chase Florell Feb 25 '10 at 18:04
  • 3
    "So I think that the advantage of multiple files will be far greater than fewer http requests..." No, no, no... exactly the opposite. With a high speed connection, the time taken handling HTTP requests is the bottleneck. Most browsers by default only download two files at a time, so the browsers would do 2 requests, wait, download the css files quickly, send 2 more requests, wait, download the files quickly. As opposed to one HTTP request for one css file it downloads quickly. The communication with the server would be the slow part. – Isley Aardvark Feb 25 '10 at 20:52
  • 1
    You can build and test features with separate style sheets and combine them into a one mongo one a build time. That way you're not maintaining one mongo file but many smaller files. We do this as well as compress out all of the whitespace and comments that make it easy on humans to read but are meaningless to your web pages. – No Refunds No Returns Feb 25 '10 at 23:22
  • Runtime concatenation is probably fine, but any further processing (like minification) is probably best left to a build process. And even if you're serving up your files with gzip encoding, minification still has some benefit. Maybe less with a faster connection, but it may be worth a look. – eyelidlessness Nov 18 '10 at 07:09
  • As a follow up to this, I've settled on using separate files in my design time, and a build process to minify and combine. Then I still have my static files and less system overhead (because I'm not doing it at runtime). – Chase Florell Nov 18 '10 at 07:16
  • I use separate files, then combine and minify automatically via PHP – Krii Mar 17 '16 at 00:11
  • 2
    It would be to have this answer updated now that http2 reduces the advantage of fewer requests. – DD. Sep 21 '16 at 11:04
  • What about the issue of css collisions. I'm thinking about a react app where each component has it's own css, but if you add some styles in Component1.css and Component2.css, I guess whichever file get's loaded last would win? – Danwize Aug 11 '21 at 17:46
99

A CSS compiler like Sass or LESS is a great way to go. That way you'll be able to deliver a single, minimised CSS file for the site (which will be far smaller and faster than a normal single CSS source file), while maintaining the nicest development environment, with everything neatly split into components.

Sass and LESS have the added advantage of variables, nesting and other ways to make CSS easier to write and maintain. Highly, highly recommended. I personally use Sass (SCSS syntax) now, but used LESS previously. Both are great, with similar benefits. Once you've written CSS with a compiler, it's unlikely you'd want to do without one.

http://lesscss.org

http://sass-lang.com

If you don't want to mess around with Ruby, this LESS compiler for Mac is great:

http://incident57.com/less/

Or you could use CodeKit (by the same guys):

http://incident57.com/codekit/

WinLess is a Windows GUI for comipiling LESS

http://winless.org/

Marc Edwards
  • 1,318
  • 10
  • 12
  • 6
    Changing my accepted answer here, since this is really the way to go these days. When I originally asked I don't feel like Sass or LESS had really taken off yet. – Nate Jul 05 '18 at 14:03
  • @nate how do you feel about this in 2023? Where [CSS variables](https://caniuse.com/css-variables) are supported and CSS nesting is [on the way](https://caniuse.com/css-nesting) – PiTheNumber Jun 15 '23 at 12:58
  • @PiTheNumber its a fair question! So much has changed since I originally asked this question. It stood as an OK question for almost ten years and was then closed as opinion based. It really depends what tools you are using. Variables and css nesting will help sites without a build step for sure. The HTTP1.1 vs HTTP2 issue is mostly behind us these days to the delivery matters less, its more of a DX issue now. – Nate Jun 15 '23 at 21:58
34

Historically, one of the main advantages x in having a single CSS file is the speed benefit when using HTTP1.1.

However, as of March 2018 over 80% of browsers now support HTTP2 which allows the browser to download multiple resources simultaneously as well as being able to push resources pre-emptively. Having a single CSS file for all pages means a larger than necessary file size. With proper design, I don't see any advantage in doing this other than its easier to code.

The ideal design for HTTP2 for best performance would be:

  • Have a core CSS file which contains common styles used across all pages.
  • Have page specific CSS in a separate file
  • Use HTTP2 push CSS to minimise wait time (a cookie can be used to prevent repeated pushes)
  • Optionally separate above the fold CSS and push this first and load the remaining CSS later (useful for low-bandwidth mobile devices)
  • You could also load remaining CSS for the site or specific pages after the page has loaded if you want to speed up future page loads.
Christophe Roussy
  • 16,299
  • 4
  • 85
  • 85
DD.
  • 21,498
  • 52
  • 157
  • 246
  • 5
    This should be the accepted modern answer RE performance. Some other replies are out of date. – SparrwHawk Dec 28 '18 at 10:01
  • If you're building an SPA (single page app) then I'd argue the best design is to build all of your css and js into two complete files. "app.js" and "vendor.js" All the html, and styles are compiled to inline JS in vendor.js That means "bootstrap.css and bootstrap.js" are all in vendor.js and it's minimized with sourcemaps into "vendor.min.js". Same thing with the app, except now you use an html to js inline transpiler so even your apps html is in the js file. You can host them on a CDN and browsers will cache them. You can even compile images to styles and into JS. – Ryan Mann Jul 02 '19 at 04:44
33

I prefer multiple CSS files during development. Management and debugging is much easier that way. However, I suggest that come deployment time you instead use a CSS minify tool like YUI Compressor which will merge your CSS files into one monolithic file.

TM.
  • 108,298
  • 33
  • 122
  • 127
Randy Simon
  • 3,324
  • 21
  • 19
19

Having only one CSS file is better for the loading-time of your pages, as it means less HTTP requests.

Having several little CSS files means development is easier (at least, I think so : having one CSS file per module of your application makes things easier).

So, there are good reasons in both cases...


A solution that would allow you to get the best of both ideas would be :

  • To develop using several small CSS files
    • i.e. easier to develop
  • To have a build process for your application, that "combines" those files into one
    • That build process could also minify that big file, btw
    • It obviously means that your application must have some configuration stuff that allows it to swith from "multi-files mode" to "mono-file mode".
  • And to use, in production, only the big file
    • i.e. faster loading pages

There are also some software that do that combining of CSS files at run-time, and not at build-time ; but doing it at run-time means eating a bit more CPU (and obvisouly requires some caching mecanism, to not re-generate the big file too often)

Pascal MARTIN
  • 395,085
  • 80
  • 655
  • 663
  • I think this great answer would benefit from at least mentioning possible css techniques to account for collisions. E.g. if you have modular css and two classes have the same name, either later class or more specific one would win leading to unexpected result in production. – Alexander Kucheryuk Aug 11 '21 at 21:34
19

You want both worlds.

You want multiple CSS files because your sanity is a terrible thing to waste.

At the same time, it's better to have a single, large file.

The solution is to have some mechanism that combines the multiple files in to a single file.

One example is something like

<link rel="stylesheet" type="text/css" href="allcss.php?files=positions.css,buttons.css,copy.css" />

Then, the allcss.php script handles concatenating the files and delivering them.

Ideally, the script would check the mod dates on all the files, creates a new composite if any of them changes, then returns that composite, and then checks against the If-Modified HTTP headers so as to not send redundant CSS.

This gives you the best of both worlds. Works great for JS as well.

clami219
  • 2,958
  • 1
  • 31
  • 45
Will Hartung
  • 115,893
  • 19
  • 128
  • 203
  • 9
    however, runtime compression/minification has system overhead. You have to weigh the pros and cons. If you have a high traffic site, this is not an optimal solution. – Chase Florell Mar 04 '11 at 18:22
  • 6
    @ChaseFlorell - you just do the compression/minification once and cache it – Siler Dec 18 '14 at 17:44
  • @Siler, I Know, that's why I posted my answer. http://stackoverflow.com/a/2336332/124069 – Chase Florell Dec 18 '14 at 17:59
13

Monolithic stylesheets do offer a lot of benefits (which are described in the other answers), however depending on the overall size of the stylesheet document you could run into problems in IE. IE has a limitation with how many selectors it will read from a single file. The limit is 4096 selectors. If you're monolithic stylesheet will have more than this you will want to split it. This limitation only rears it's ugly head in IE.

This is for all versions of IE.

See Ross Bruniges Blog and MSDN AddRule page.

TheClair
  • 721
  • 4
  • 8
8

There is a tipping point at which it's beneficial to have more than one css file.

A site with 1M+ pages, which the average user is likely to only ever see say 5 of, might have a stylesheet of immense proportions, so trying to save the overhead of a single additional request per page load by having a massive initial download is false economy.

Stretch the argument to the extreme limit - it's like suggesting that there should be one large stylesheet maintained for the entire web. Clearly nonsensical.

The tipping point will be different for each site though so there's no hard and fast rule. It will depend upon the quantity of unique css per page, the number of pages, and the number of pages the average user is likely to routinely encounter while using the site.

Claud
  • 937
  • 1
  • 12
  • 27
  • Yes. This is question I came here about. Everyone focuses on development vs production. Of course your development environment can be different from your live site, but which is better for the live site? No one seems to really address this. Do you know of any resources on finding where the tipping point is? – Dominic P Jan 15 '15 at 19:58
6

I typically have a handful of CSS files:

  • a "global" css file for resets and global styles
  • "module" specific css files for pages that are logically grouped (maybe every page in a checkout wizard or something)
  • "page" specific css files for overrides on the page (or, put this in a block on the individual page)

I am not really too concerned with multiple page requests for CSS files. Most people have decent bandwidth and I'm sure there are other optimizations that would have a far greater impact than combining all styles into one monolitic CSS file. The trade-off is between speed and maintainability, and I always lean towards maintainability. The YUI comperssor sounds pretty cool though, I might have to check that out.

Nicholas Cloud
  • 1,564
  • 1
  • 13
  • 19
  • This is what I do, and it's been working well for me. At most you get 3 css files for each page, which is pretty reasonable – Ricardo Nunes Mar 19 '15 at 18:35
4

I prefer multiple CSS files. That way it is easier to swap "skins" in and out as you desire. The problem with one monolithic file is that it can get out of control and hard to manage. What if you want blue backgrounds but don't want the buttons to change? Just alter your backgrounds file. Etc.

Robusto
  • 31,447
  • 8
  • 56
  • 77
  • the problem is that this is quite selfish on a developers standpoint. Once you're done, you rarely have to go back in, but your visitors all have to wait for pages to load unnecessary css files. (Same goes for Javascript in my opinion) – Chase Florell Feb 25 '10 at 18:41
  • 7
    @rockin: In checking one of my 5-CSS-file sites after clearing my cache, I discovered that the total time it took to load all CSS was less than a 10th of a second. If people can't wait that long, I think they need more Ritalin or something. What is a much bigger problem is callbacks to ad sites like doubleclick, etc., which can result in HUGE delays, as witnessed on this very site within the past week. – Robusto Feb 25 '10 at 19:38
  • A great tool to use to test site speeds is Firebug in conjunction with YSlow. This should give you an accurate representation of your site's speeds. – Chase Florell Feb 25 '10 at 20:06
4

Maybe take a look at compass, which is an open source CSS authoring framework. It's based on Sass so it supports cool things like variables, nesting, mixins and imports. Especially imports are useful if you want to keep seperate smaller CSS files but have them combined into 1 automatically (avoiding multiple slow HTTP calls). Compass adds to this a big set of pre-defined mixins that are easy for handling cross-browser stuff. It's written in Ruby but it can easily be used with any system....

stikkos
  • 1,916
  • 2
  • 19
  • 34
3

here is the best way:

  1. create a general css file with all shared code
  2. insert all specific page css code into the same page, on the tag or using the attribute style="" for each page

on this way you have only one css with all shared code and an html page. by the way (and i know that this is not the right topic) you can also encode your images in base64 (but you can also do it with your js and css files). in this way you reduce even more http requests to 1.

2

SASS and LESS make this all really a moot point. The developer can set up effective component files and on compile combine them all. In SASS you can toggle off the Compressed Mode while in development for easier reading, and toggle it back on for production.

http://sass-lang.com http://lesscss.org

In the end a single minified CSS file is what you want regardless of the technique you use. Less CSS, Less HTTP requests, Less Demand on the server.

augurone
  • 107
  • 5
1

The advantage to a single CSS file is transfer efficiency. Each HTTP request means a HTTP header response for each file requested, and that takes bandwidth.

I serve my CSS as a PHP file with the "text/css" mime type in the HTTP header. This way I can have multiple CSS files on the server side and use PHP includes to push them into a single file when requested by the user. Every modern browser receives the .php file with the CSS code and processes it as a .css file.

  • So if I'm using ASP.NET an .ASHX generic handler would be the ideal route to go, that combines them into a single file to get the best of both worlds? – Nate Feb 25 '10 at 18:01
  • Yes, I would use an IHttpHandler to combine your CSS at runtime (see #2 in my answer above) – Chase Florell Feb 25 '10 at 18:03
  • @Nate: When I was working in ASP.Net we used template files to accomplish the same thing. – Robusto Feb 25 '10 at 18:03
  • @Robusto, could you explain what a template file is? I don't think I've ever heard of it. I have used App_Themes, but that still doesn't combine CSS. – Chase Florell Feb 25 '10 at 19:36
  • We used XSLT templates. Have you never used those? Look at http://www.w3schools.com/xsl/xsl_templates.asp. – Robusto Feb 25 '10 at 20:01
  • No I have never used those, I use strictly code based solutions. You had mentioned that you did it while working with ASP.NET, so I suppose I was trying to put the idea of "template files" into the context of "ASP.NET". – Chase Florell Feb 25 '10 at 20:10
  • 1
    just as an update. Using an IHttpHandler or a PHP file to combine css on the server side may save bandwidth and speed up requests, but it also adds unneeded load on the server. The best way to do this is to combine/minify your css/js during the build/publish of your site. This way you have a single static file that doesn't take any server processing. Best of ALL worlds, bar NONE. – Chase Florell Jun 23 '11 at 02:21
1

You can just use one css file for performance and then comment out sections like this:

/******** Header ************/
//some css here

/******* End Header *********/


/******** Footer ************/
//some css here

/******* End Footer *********/

etc

Catfish
  • 18,876
  • 54
  • 209
  • 353
  • 4
    That doesn't make it easier to maintain, as I still need to scroll through miles of unrelated css to get to what I'm after... – Nate Feb 25 '10 at 18:03
  • 2
    @Nate: Have you considered switching to a text editor with decent search functionality? My personal preference is a single css file and I never scroll through it. I just type "/classname" (I use a vi derivative) and *bam* - I'm at that class. – Dave Sherohman Feb 25 '10 at 18:27
  • 3
    It's also harder to maintain in a multiple-developer environment. What is a "header" in your above example? What if someone else is not thinking geographically, but in terms of basic design elements, like buttons or menus, while others are thinking differently? Where does a menu go if it's in a header? How about if it's not? I think it's easier to enforce that kind of discipline in separate files. Why don't application developers just create one huge application class with all the trimmings instead of a framework with class hierarchy? Seems similar to me. – Robusto Feb 25 '10 at 19:44
  • What if you don't remember the name of the class you are looking for? Or how do you decide where to add a new class? – Nate Feb 26 '10 at 15:41
  • If it's just a couple page website it's really not that big of a deal. Just suggesting another way to do things. – Catfish Feb 26 '10 at 16:25
1

I'm using Jammit to deal with my css files and use many different files for readability. Jammit doest all the dirty work of combining and compressing the files before deployment in production. This way, I've got many files in development but only one file in production.

jlfenaux
  • 3,263
  • 1
  • 26
  • 33
0

A bundled stylesheet may save page load performance but the more styles there are the slower the browser renders animations on the page you are on. This is caused by the huge amount of unused styles that may not be on the page you are on but the browser still has to calculate.

See: https://benfrain.com/css-performance-revisited-selectors-bloat-expensive-styles/

Bundled stylesheets advantages: - page load performance

Bundled stylesheets disadvantages: - slower behaviour, which can cause choppyness during scrolling, interactivity, animation,

Conclusion: To solve both problems, for production the ideal solution is to bundle all the css into one file to save on http requests, but use javascript to extract from that file, the css for the page you are on and update the head with it.

To know which shared components are needed per page, and to reduce complexity, it would be nice to have declared all the components this particular page uses - for example:

<style href="global.css" rel="stylesheet"/>
<body data-shared-css-components="x,y,z">
Steve Tomlin
  • 3,391
  • 3
  • 31
  • 63
-1

I've created a systematic approach to CSS development. This way I can utilize a standard that never changes. First I started with the 960 grid system. Then I created single lines of css for basic layouts, margins, padding, fonts and sizes. I then string them together as needed. This allows me to keep a consistent layout across all of my projects and utilize the same css files over and over. Because they are not specific. Here's an example: ----div class="c12 bg0 m10 p5 white fl"/div--- This means that the container is 12 columns across, utilizes bg0 has margins of 10px padding of 5 the text is white and it floats left. I could easily change this by removing or adding a new - What I call a "light" style- Instead of creating a single class with all these attributes; I simply combine the single styles as I code the page. This allows me to create any combination of styles and does not limit my creativity or cause me to create a massive number of styles that are similar. Your style sheets become a lot more manageable, minimized and allow you to re-use it over and over. This method I have found to be fantastic for rapid design. I also no longer design first in PSD but in the browser which also saves time. In addition because I have also created a naming system for my backgrounds and page design attributes I simply change out my image file when creating a new project.(bg0 = body background according to my naming system) That means that if I previously had a white background with one project simply changing it to black simply means that on the next project bg0 will be a black background or another image..... I have not found anything wrong with this method yet and it seems to work very well.

raquel
  • 1
  • 12
    Do you know what paragraphs are for? – Em1 Oct 26 '12 at 09:37
  • This is "UI Framework" like unto Bootstrap or others, once you know the lexicon you are good to go, it is all about the learning curve and acceptance of the terms used. Still though I can think of some very specific instances where your example will struggle to meet the designers requirements. – augurone May 17 '13 at 19:47