I've been reading up about responsive design and am going to start implementing a new CSS set-up on my site. This has lead me to thinking about the best way to call all these different CSS files. I'll have a different CSS for different screen widths.
I am debating two options:
connecting to all the files from each web page with LINK tags. My only problem with this is the ongoing maintenance (and having to add all these links to start with); I know this isn't the end of the world but seems a little bit intensive on the maintenance side.
the other way would to have just one LINK tag on each web page, pointing at a 'feeder' CSS. This 'feeder' CSS file would include all the links to my other CSS files using #imports. This would mean maintenance would be a breeze. I could add/re-order/delete the CSS files in just one place for the entire site. Great!
However this leads on to compatibility of the #import function [or lack of it in older browsers].
I've looked around and the articles I've seen have been at least a couple of years old.
So, to get to the nub: what percentage of browsers that are being used now [July 2013] support this and can I safely forget about the browsers that wont be able to interpret #import?
If not, what can I do to keep maintenance of CSS files down to a minimum. (Something more elegant than "find and replace on current site").
Instead of worrying about #imports, you should just combine and minify all of your CSS files that cannot be served via a CDN:
<link rel="stylesheet" href="styles-84e599dcbd6c60fa0af76aaa18a5d75f.css" />
It'll load faster, use up less bandwidth, and will work on any browser that supports stylesheets.
There are many ways to do this. If you're not using any web framework (or are using Node.js), take a look at Grunt.
As for your actual question, unless you're planning to support browsers older than IE5.5, #import will work just fine. But I strongly recommend the minified stylesheet approach.
I'm going to actually say that the accepted answer, now in 2016, is not necessarily the correct one-- for a couple of reasons:
1) HTTP 2.0 is becoming the majority-used protocol version in industrialized countries outside of China (thanks, old IE), and will soon be considered the industry standard (if it's not already). This means that support for connection multiplexing and header caching eliminates the need to combine files into one; in fact, at the Fluent Conference in SFO last year the HTTP2 presenter actually argued that splitting things like CSS and images into multiple files will actually be better due to HTTP's superior ability to utilize more bandwidth due to longer connection times.
2) Because of all this front-end automation in CSS like SASS and LESS, you end up much more likely to break the IE 5-9 4095 selector limitation. This is a little known bug because until now people rarely exceeded that number of selectors in a single sheet; however, on enterprise sites this is becoming a common thing. Basically, any sheet with more than 4095 selectors will still be read in, however the browsers will simply silently fail to render any rules after that.
This isn't to say that minifying into one file is bad, however, the other approach of splitting is actually no longer bad either, and in fact, in certain cases is either necessary or even better depending on project needs.
Here are some stats about browsers http://www.w3schools.com/browsers/browsers_stats.asp
For responsive css I would use media queries, it wont affect older browsers, and work great for devices that are going to need the responsive css (mobile devices)
http://css-tricks.com/css-media-queries/
This question already has answers here:
Would it be a bad practice to use less.js in a production site (client-side javascript compliler for LESS style-sheets)?
(4 answers)
Closed 1 year ago.
Just getting into the fun world of CSS preprocessors. Let's say we're using LESS to render our CSS. I'm wondering about two different approaches:
Using LESS to render the CSS on every page load.
Using LESS as part of the Build Process and just using the rendered CSS in production.
I'm wondering if there are times where you'd use one and not the other. On one hand you have dynamic CSS a runtime and the other static CSS build from a (hopefully) concise and clear LESS template.
This is an article written on CSS-Tricks from Chris Coyier
Chris says that it is possible, with LESS, to use an .less file using the link tag like you do with normal .css files
<link href="style.less">
Although this is one way to process the file, it is not the most efficient way to do it. It could severely slow down loading cases, and it could possibly crash the browser It would be better to use the LESS gem to convert the LESS into CSS. As Chris says,
The "pre" part of preprocessing you can think of as "before you send these files to the live website."
Here is a good article that explains the different ways you can process the .less files.
On the Client-Side compilation, the writer sums it up nicely
Rather than the Sass/LESS code being compiled once, it’s compiled on every single page request — and to make matters worse, you’re passing that burden off on your users, rather than doing it yourself
For your second point, that is essentially what CSS preprocessors were built for. They were made to have a manageable CSS script that is high in readability, and low in difficulty of change. Then, you don't even have to look at the CSS file. Just ship it off to the land of the browsers, where it will get torn apart anyway by browser specific renderings (cough, cough IE).
I recently stumbled across a project that has 27 different CSS files used by the same theme, and they are for specific sections in the application, rules split like this: there's a CSS file for the menubar, there's two more files for contact forms, another one does the footer, specific-page formatting, two more for galleries, so on.
So I asked lead what's the reasoning for so many CSS files and if it's safe to concatenate.
His reply was that all files sum 126KB, bandwidth matters and there's 500+ CSS rules, so best not concatenate to prevent selector collisions.
I know that 126KB of uncompressed CSS files is an awful lot, but I also know (from the best practices guide) that all these files should be downloaded single shot, so browsers will cache one biggie instead of downloading them one by one across the browsing session.
Why should I not keep myself from gluing all these files together? Is it a big deal?
Due to how cascading works, there is no possible way to cause harm just by concatenating the files together, provided you keep them in the order they appeared in the source. This will ensure that later files overriding earlier ones will still do so.
Then, you can consider minifying the CSS. This won't change the function of the selectors, but will compress them to reduce bandwidth.
All in all, having 27 CSS files is just stupid. The user would have to wait for 27 connections to be established, requests to be made, and downloads to be completed, just to see the page. Now, this does improve somewhat with proper cacheing, but even so...
Why should I not keep myself from gluing all these files together? Is it a big deal?
If you know that the CSS files do not have any conflicting directives and that they should be loaded in the same order for each page in the application, then you should, in fact, bundle them into one minified CSS file.
But that's just it. Typically when you find yourself in this situation, it's extremely difficult to discern which CSS directives are applied to which screen(s).
Emphasis: The situation that you are facing indicates technical debt.
While I agree that 27 CSS files is utterly nuts, and that ideally it should be merged and minified, there are some use cases where dividing stylesheets make sense.
Consider this:
You are working on a subsite, which requires a large number of CSS rules, that are not otherwise used on the site. If there is no guarantee that the user will visit both the sub site and the main site (and therefore take advantage of caching), it makes sense to keep two stylesheets, so the browser doesn't have to read through a huge stylesheet to see if anything matches the HTML document.
Now, this is no common case, but it does happen. An example would be a large corporation, with a lot of subdivisions with their own sites. They might include one stylesheet for all their shared styles (corporate specific UI and so on) and separate stylesheets for layouts and overrides.
That said, I very much doubt that 27 stylesheets would ever make sense. The original author probably didn't have a clue, and thought it was more structured that way. Modularized CSS is actually pretty neat, but it should always be merged and minified before it reaches the client. This is the common work method in SASS. You will have a lot of partial stylesheets for specific parts or functions of the site, but as soon as you hit Ctrl+S, it's automagically merged into one neat little package.
Now, you could probably figure out in what order the CSS files on your site is loaded, simply by visiting each page and noting the order. It would be tedious work, and there's no guarantee it will ever really pay off, but it can be done.
Once upon a time I was thought by more advanced web developers (gee, when was it again? ;)) that we should avoid managing multiple CSS files and stick to one per project. It helped to improve page load speed and avoid silly mistakes when dealing with a lot overlapping CSS rules.
My question is - is this approach still valid?
Argument about page load performance doesn't seem to hold that much nowadays with awesome broadband Internet and clever web browsers with even more awesome caching capabilities.
CSS cascading can indeed be error prone, but just for inexperienced developer and having one CSS style sheet doesn't really make us bullet-proof.
I think that I would prefer to have a set of default style sheets neatly separated by components, then wire them up into one single rule by CSS #import. This would also allow me to include reset style sheet by default.
Anyone is with me?
It's not about bandwidth speed but number of http requests, this makes a lot of sense for a mobile connection.
However the approach of having different css files to keep the project modular is solid, as it helps you keeping your css organized the way you want it without having all the code in one file only. Then you can benefit of css preprocessors / minifiers to concatenate and compress all your css files in a single one for production.
this article http://www.igvita.com/2012/06/14/debunking-responsive-css-performance-myths/
has a paragraph about mobile that explains well why this is a good practice:
you are much better off downloading all of the CSS content in one shot over the initial, warmed up connection. By doing so, you will also help the user extend their battery life. If there is one optimization to be made here then it is simply: concatenate and compress.
Yes, that approach is still valid. There are dozens of articles about load optimization out there, but the general idea is as follows
Less files = less http requests made to server = better load performance
Main thing that changed over time is that now there are many tools that support merging multiple files into single at runtime. So you have separate stylesheets for better organization, debugging at development time, and those tools merge, minify and set correct caching headers at production.
I agree with you, I find no reason to keep only a single css sheet anymore, nowadays, I do exactly what you just stated, separation by component, along with lazy loading :) (php if statements etc).
I separate stuff with comments. For example divs goes to /* Divs start*/ div#somediv /* Divs end*/ /* Animations start*/ /* Animations end*/. For me this is easier than merging different css files once i've completed the project
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
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
positions.css
buttons.css
tables.css
copy.css
vs.
site.css
Have you seen any gotchas with doing it one way vs. the other?
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.
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/
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.
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.
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.
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)
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.
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.
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.
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.
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....
here is the best way:
create a general css file with all shared code
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.
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.
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.
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
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.
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">
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.