Modularizing CSS files - css

Many people say to keep the number of external CSS and JavaScript files to minimum to reduce round trip time. For example, Google recommends maximum two CSS and JavaScript files per web site, respectively.
The problem is, I've broken up CSS code into several files depending on its nature as part of "modularization". For example, I've put CSS code that is only used in a certain part of the application in a separate file. As a result, some files have less than a hundred lines of code.
I'm a Java develper, and this is actually a recommended practice in Java, but CSS is a totally different creature and I don't know much about CSS. Here are my questions.
Does it make sense to keep as many CSS files as you see fit for readability and maintainability?
How many CSS files are manageable in a web project?
What's the average number of CSS files in web applications that you've worked on in the past?

The best solution is to write a script that combines (and minifies) multiple CSS or JS files.

You might benefit from a solution like Bundler, or Chirpy
http://www.codethinked.com/bundler-now-supports-css-and-less
http://chirpy.codeplex.com/
We use chirpy because we found a bug in Bundler that can inject query string params into you css files.
As a bonus to file consolidation, you also get .less syntax handling.

I agree with what other have said here, yes when you develop you have muliple CSS files, but for production you should merge an minify them.
However I do not agree you should merge them all into 1 single file. As the will mean people who just want to visit your home page must wait for CSS on pages x,y,z also to download.
What I usually do is have 2 or 3 CSS files.
1 small CSS file just for the home page only so it load super quick so casual visitors do not have to wait to see what my site is about
Another CSS file for every other page availble to guest users
Another CSS file for a members only sectons of the website that require a login.
You can also use scripts like HEAD.JS which will manage your CSS and javascript asynchronously
From there site http://headjs.com/
There is a common misbelief that a single combined script performs best. Wrong:
latest browsers and Head JS can load scripts in parallel. loading 3 parts in parallel instead of as a single chunk is usually faster.
if an individual file is changed the whole combination changes and you loose the benefits of caching. it's better to combine only the stable files that doesn't change often.
many popular libraries are hosted on CDN. you should take the advantage of it instead of hosting yourself
iPhone 3.x cannot cache files larger than 15kb and in iPhone 4 the limit is 25kb. And this is the size before gzipping. if you care about iPhones you should respect these limits.

As you point out, having multiple CSS files often leads to better maintainability and modularity.
The number of CSS files needed depends on the size of your project and the level of modularity in the project.
Serving up on CSS file instead of many often makes a noticeable difference in the page loading time, so the ideal solution is to have some kind of tool that combines, and maybe even compresses, the CSS files. This can easily be done in runtime by a tool such as Minify.

Combining resources can be beneficial in that it can reduce the number of HTTP requests; Reducing the number of HTTP requests certainly lowers overhead and can improve performance. It can also have benefits for caching, in that there can be fewer objects in the cache.
That said, this kind of optimization is only useful with metrics. There are profilers out there (Firebug has one) that can show you how many requests you're making and how long they take. You may (or may not) find there are more time-effective ways to increase performance and reduce load on your server.

Related

All CSS in 1 or more files?

Does the fact that I have 1 or 30 css files have any effect to my website?
I know that I have to have special file for print, but right now I speak about rest CSS I can have in 1 file, but I split it into 30 files.
Yes, there are performance implications to having large numbers of separate files to download; you will improve your site's performance by combining them.
The number of HTTP requests made by a page is a significant factor in page loading time, because:
the browser has to wait for all requests to finish before it can render the page correctly and before it can call any Javascript that is set to run on page load.
browsers have a limit on the number of HTTP requests they can make simulataneously. In some browsers, that limit is very low (as low as 2 for old IE versions).
your server will also restrict the number of simultaneous requests.
All of these issues will slow down your site if you have a lot of separate files.
There are good reasons for having separate files -- eg for caching, if some files change more often than others, you may not want them to be merged with others that never change -- but for the most part, you should do you best to reduce the number of HTTP requests your page has to make.
Don't feel that you have to merge them all into one single file, but you should definitely consider reducing the number as much as possible.
In addition, IE8 and earlier have quite tight restrictions on the number of CSS files allowed -- it only allows 31 CSS files; any CSS files over that limit are ignored. You may not have hit that limit yet, but it sounds like you're getting dangerously close to it, and it has the potential to bite you very hard if you don't know about it. This problem is also solved by simply merging your CSS files.
Yes, it does. The less HTTP requests you have, the faster loading process is.
You can analyse loading speed with YSlow
Yes, it does affect the speed of your site.
Browser can donwload a limited number of resources at a time (=in parallel - it differs between browsers, but it's around 4 sources from one domain), so they are "blocked" if you have too many separate sources resulting in a lot of HTTP requests. The browser has to wait to complete these requests and can't continue with the creation of the document during that time.
You should always try to use as few files as possible, minify them and possibly compress (gzip) them.
Yes it certainly does, especially if you are loading all of them on one page load. 30 http requests instead of 1 will make a big difference.
CSS Preprocessors
If you feel that having your css files separated offers you a benefit of readability and the such then it is worthwhile looking into using a css preprocessor such as Less or Sass as these will allow you build seperate files into one style sheet.

I need your opinion on CSS optimization

Lately I’m reading a lot of CSS optimization, and I notice that almost every article, recommend to put ALL your styles in ONE file.
I understand the thinking behind this, but this is practical? I mean I’m working in a fairly large project and by now I have a huge amount of styles. I think it will be very difficult to maintain with everything in one file.
My question is: the performance gain is that big to justify the complexity of having all in ONE file?
Thanks!
Edgar.
UPDATE
Just to clarify, I’m sure about the need to optimize the CSS. Actually, I have a process in place that minimize and compress the CSS files, and I do everything that I can to not repeat myself.
My doubt is exclusive about the practice of using one big file vs multiple files.
Let’s put this example:
My application has multiple modules, for example: contacts, projects, accounting, HHRR, etc.
I have one CSS file for each module, plus a couple of other general CSS files like: reset, layout, forms and so on.
When I’m using the CONTACTS module, I load the general files plus the contact.CSS file. I skip the
rest of the CSS because they are not needed.
Now to the Math, let’s say that each CSS file is around 10KB,
My current way:
About 50kb in general files About 5
downloads request in general files
About 10k in customer file One
download request.
This is a total of about 60kb and 6 download request.
The one file Method:
About 120kb (all the files together including styles that are not used at the moment) in one file
One download request.
So, in your opinion, the beneficial gain of using one big file and only one download request, justify all the extra work of implementing a method of combining all the files together and all that hassle?
For development, keep them separate. CSS can quickly become a nightmare. For production you should build in a process to combine, minify and compress all your files into one.
It's a great idea to compress your CSS like that, as it saves bytes and makes the page load faster.
When you develop your site, of course don't minify the code. It's pointless, as your local webserver is as fast as can be. But when you deploy your site, minify the code. It saves you bandwidth and makes your site more responsive for the end user.
Here's a sample chunk of CSS that I would use:
/* 33 characters */
body {
background-color: red;
}
When compressed, it's a bit smaller (81% of the original size):
/* 27 characters */
body{background-color:red;}
You can make a script to compress the CSS, as you shouldn't do this by hand. Google "css minifiers" and I bet you'll find a ton.
Do both. Develop in multiple files, then just have a process which combines, compresses and minifies (removes comments, spaces, etc) them into one file when you deploy.
It's not really a performance gain so much as a bandwidth gain. Each file that the browser must fetch represents about 200 extra bytes. You can have a program that combines multiple CSS files into one for deployment, but most CSS minifiers will do that for you.
I`m surprised that nobody mention one very obvious reason to do that.
In a big site, you will have many elements to load, especially visual elements - images. Think about how many files your site is loading. You can load a limited number of files from a single domain at once. And CSS is bringing some background images and sprites. There is no point loading 2, 3 or more CSS file.
Minification as Blender suggests is a bonus to your bandwidth. 2K is more is noting for a single user, but multiplied by 1 000 or 10 000 is a lot. And if you minify a CSS, what about the HTML? I haven`t seen so many pages with minified HTML!

Performance, serve all CSS at once, or as its needed?

As far as I know, these days there are two main techniques used for including CSS in a website.
A) Provide all the CSS used by the website in one (compressed) file
B) Provide the CSS for required by the elements on the page that is currently being viewed only
Positives for A: The entire CSS used on the site is cached on first visit via 1 http request
Negatives for A: if it's a big file, it will take a long time to load initially
Positives for B: Faster initial load time
Negatives for B: More HTTP requests, more files to cache
Is there anything (fundamental) that I am missing here?
Profile it. It depends on the way your users use your site.
If it's a web application and your users are likely to interact with it a lot and see most of the layout you designed, you probably want to use a single CSS which is loaded once and then stored in the browser cache. The first time overhead is negligible in this case.
If most of your users come with a cold cache and just look at two or three pages, separate CSS files will probably improve their experience.
You can't tell without having a look at what the users actually do.
Even a largish CSS file, gzipped, is tiny compared to a lot of other things (like images, movies, etc.) that get downloaded. The only real reason to break up CSS into separate files is to swap in special rules to make certain browsers behave (I'm looking at you, IE).
There is no A or B, it's always a trade-off between the two. For example: you'd want the front-page to load as quickly as possible, so you only request what's necessary. For the following pages you request the remaining CSS. A total of 2 requests.
In essence, you're creating packages/groups of related CSS. By dynamically combining and compressing these packages, you can create a maintainable structure of files. This also enables you experiment with the best combination of speed, performance, requests and bandwidth...
This whole story also applies to JavaScript files, since the same trade-offs can be made.
What's better?
Writing one css file
Writing more css files
What's better?
Tracking, keeping 1 css file updated
Tracking, keeping more css files updated
What's esier?
Making decisions what to insert into one css file
Deciding what to put in every of your css files
What's the cost of generating each individual css file compared to generating one global css file.

For performance, use one or several css files?

I'm wondering if it's better to make one or several files for CSS files ?
I always see websites with a plenty of css files, but it seems better to use only one large file.
What's your advice ?
Performance wise, you are better off with a single file, as it results in one connection and request to the server (these tend to be expensive operations, time wise).
This is why minifying frameworks exist, that merge together all the CSS (and JavaScript) files for each page and serve them in one request.
My strategy on this is simple.
I separate production from development, both in CSS files and in JS files.
in development, I can have up to 20 JS files and 10 CSS files, organization is super slick and easy, I always know where everything is.
In production, all files are minified into 1js and 1css file, changes are always made in development and then "staged" to production so I gain the maintainability of the application and the performance in production.
I use Yahoo minifier to minify my files but you can use whatever is convenient for you.
Having one CSS file doesn't just help with HTTP requests, it will also give you better compression (compressing one big file should give you better results than compressing multiple smaller files).
Different HTTP requests are hardly the bottleneck here, file size ultimately is. The reason it's best to split things up as much as possible is because if you want to change a certain thing of your site's feel, let's say, the font of all headers, you want to change one file / setting only for that, and want that file to be as small as possible.
For large and encompasing CSS, I would make different CSS documents for all different things like the layout, the treatment of classes, and so on, another advantage is that if you've multiple pages that need a slightly different look from the main page, they only have to link to one other CSS file, not to a completely different one, the majority they an share.
If performance does matters to you
Then
If your site is small but gets huge traffic then go for one css file
if site is small personal or business sites then but with less traffic then go to multiple css
If CSS files maintainability does matters to you
Then
If your site is small with less different pages then go for one css file.
if site is big then go for multiple css http://www.killersites.com/blog/2008/how-to-organize-css/
HTTP request of CSS files will not make big difference in performance of small site.
Use not too much different css files or at least try to put them on other domains to speed up downloading them by the browser. I also suggest you use a minification tool.
Well, the same as Yahoo!'s: Use one to reduce the number of HTTP requests.
For the quickest download and rendering of a page, the Yahoo performance rules are correct. You want as few http requests as possible.
However, on many sites, it's simply not convenient to have a single large CSS files. Your best bet is to organize your CSS into as many files as you'd like, and then use a server side script to concatenate the files. GZIP'ing that file goes a long way, too.
you should use more than one css file rather using one big file. It helps you while maintaining your site also use different definitions (classe or id names) in different css otherwise it will take the one which declared later.
But for performance reasone you can use one large file because,
One large CSS file leads to fewer HTTP requests, which can improve performance.
Several smaller files leads to easier organization which will make development and maintenance cheaper and easier.
Multiple files are good for organization, but one request to the server is definitely best. If you watch the performance videos from Google they suggest the least amount of HTTP requests possible. Each HTTP request has overhead in the handshake that you do not want to incur if you wish your site to be fast.
Check out this great script which will take your multiple CSS/JS files and turn them into one file:
http://code.google.com/p/minify/
Weigh it up.
The advantages of one CSS file
Reduced latency. Each downloadable component comes with a small amount of latency. Less files => less latency
Single point of compression
Advantages of multiple
Change one file won't require all css to be re-downloaded. The other css can be served from the cache
Structure
Only download what you need. If you don't have any forms on your page for example you don't need to download forms.css

Single huge .css file vs. multiple smaller specific .css files? [closed]

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.

Resources