What are pros and cons of using large CSS files? - html

Let's say I create 100 selectors inside style.css with a following pattern:
.width-1 {width: 1%;}
.width-2 {width: 2%;}
/* up to... */
.width-100 {width: 100%;}
Also do the same with height, table of colors and include many other styles. The final result might be a css file containing about 5000 selectors and taking 300kB of size.
The question is: Why should or shouldn't I do this? Will too many selectors cause performance issues?
Pros:
One large css file requires only one http request,
I can load a lot of css features for every website, just in case,
Cons:
Obviously - large css file size,
IE 8-9 can contain only 4095 selectors max in one css file,
There is a risk of loading too many styles which won't be used on current view.
I'm interested in targeting Android 2.3+ and IE8+

The one large file thing isn't too bad. That's why we minify/concatenate our stuff into single files. The problem is when you're using that many utility classes and a lot of them won't be used. Every selector will make the browser look up all elements of that class. So that's a whole lot of (worthless) checking to see if something's there.
If you want to have a whole bunch of utility styled things for easy usage you should consider making some mixins in sass or less. That way your css won't contain as many unused / useless content (and selectors).
So I wouldn't say that the filesize is bad, it's more the extreme slowness and uselessness of the selectors you're showing.

It's obviously stupid to add each and every width, height, color and more to a separate class each. That's is just a workaround for inline CSS. You might as well just use inline CSS and everyone will be better off.
To answer your question:
using a large CSS-file can have big performance issues.
using many CSS files might not be be an option too. iOS supports only a limited number of included CSS files per document. (I can't find the reference
Conclusion: don't. Do like everyone else and define a style for a specific class like CSS was meant to be.

Related

How strictly should I keep styling separated from the html code?

What is the most common or accepted way to prioritize between clean html code and clean css code?
As I see it there are two possible approaches…
Either you can go for a html code with minimal markups related to styling. The downside is that the css tend to be a bit messy and perhaps a bit redundant when you for example add similar styling to different objects (which in this approach lacks suitable classes).
The other approach results in a cleaner css code where you have predefined classes for different stylings, think w3.css or bootstrap. This time the downside is that you may end up with a html code that heavily relies on the class attribute of the tags, sometimes the combination of several classes; meaning that the html markup isn’t really separated from the styling.
I realize that there is no definite answer and that the line between the two options are floating. But what is the preferred approach, given that you are not using any precompiled framework?
Edit:
The question is not about inline css. It is about how to think regarding the use of predefined css classes. For example… if you add a class similar to “w3-panel” to some divs then you effectively add some margin in the html code. If you instead target those divs specifically by using selectors you keep the html free of styling.
The former produces cleaner css code and the latter produces cleaner html code. Which route is the most accepted one when not implementing a framework (forcing you to style by adding classes to the html)?
The advantage of the separation is to make it easier to maintain and if you find a css too messy, take a look for SASS or SCSS. And if you are using jQuery to manipulate your CSS, it is easier if you have your definitions in a CSS file. Imho the worst choice you can make is to mix it up - some definitions in CSS and other in the HTML - you may find it useful now, but try to change the site in a few months.
It really depends on your business of application.
If you put styles in same file in html file size would be increasing and it would be getting messy when you added new css each type, but as your css and html are in same file and css is well written and used, page load time would be minimum as html find css in same file.
If you put styles in separate css file, it would be well readable and accessible, you would have separate layer for styles and markup. But each your page load, your included css file would also be load in addition hence increase page load time.
If your application or html page is one time i.e no much furthur additions in future and will be remain same mostly then no need for separe css file.
If your application would be growing or html page being updating quite often, then you should be separate css files.
Personally, I think it is best from the beginning to split the code as much as possible. (HTML for markup, CSS for styling, etc).
Pro(+)
It is easier to troubleshoot
You can scale and later on introduce support tools such as SASS for CSS, etc.
A task can be splitted between persons.
Easier for another programmer to understand the setup of files.
Neg(-)
Take a bit energy to be disciplined and really keep coded splitted.
You sometimes would need a larger monitor to have the splitted codes in parallel view.

Does too much CSS affect performance of a web site?

I have researched on this topic and i could not find the exact answer i needed.
For example i have so many divs that need a border. I could write a seperate css class like
.border{
border: solid;
border-color: #C6C6C6;
border-radius: 5px;
}
and use it in every div tag that needs a border. Or i could include
border: solid;
border-color: #C6C6C6;
border-radius: 5px;
properties to each and every css class i'm writing for my divs.
By writing a seperate class for border and using it reduces a huge chunk of lines in my css file. But my problem is, will it affect the performance of the web application if i include border properties to each and every css class i write for my divs.
Thanks in advance.
The answer is yes ! Best practice is to have generic class.
Some documentation about CSS methodologies : http://codetheory.in/an-overview-of-oocss-bem-smacss/.
OOCSS, BEM and SMACSS are good methodologies to organize your css.
To be fair this is quite a loaded question...
I don't know if you are aware but CSS stands for Cascading Style Sheets, it was built to 'cascade' down from sheet to html tag. So the short answer is no, with today's internet connections, probably not. However here's a few things to consider...
1) Minifying the CSS -
The best way to save on performance using CSS is 'minify' it. There are many online generators that can do this like this one https://cssminifier.com/. This will remove any characters that unnecessarily take up kb in the document, such as spaces and line breaks for example.
2) User Experience -
Users in countries like the USA or the United Kingdom now for the most part have access to high-speed broadband, but you must consider that on some very very old connections you'll find that having to re-draw that rule from each tag can take time.
3) Readability and Debugging -
If you need to come back tot hat code later and decide that you want to change the border colour, you're doing to have to do that on each and every tag to apply that change as opposed to one simple change on one style sheet. Also if you try to debug this using and kind of in-browser development tool you'll find this is also more complicated that simply looking up one value on one rule instead of however many tabs this is being applied to.
4) The Cascade Effect -
Finally, this completely defies the point of the CSS model in the first place as their styles trickle down from rule, to style declaration (in the html header), to tag, which makes both documents, not only easy to read but easy to edit too.
So in short, yes there is a performance benefit, but not noticeably so unless on an older connection, but the benefits in other areas of development are much stranger than just the loading speed alone.
By writing too many CSS code could make you CSS file size big. If you could avoid duplicate lines of code by creating a class then go for that . It's a best practice to avoid duplicate code so that if any change require with changing one line of code it will reflect every where.
So if it's possible avoid duplicate code. And aways minify your CSS for production website so that CSS file will be smaller as a result page loading time could be improved.
You're trying to solve a problem you're not yet having. Don't worry about optimisation until you need to.
On a wider scale, the amount of CSS rules you have can affect the load time of your website. When your browser encounters CSS it stops rendering the page, parses the CSS, and builds the CSSOM (CSS Object Model).
So even if you minify, compress, and merge your CSS files, an excessive amount of CSS could still slow down your website.
It sounds like you're miles away from having to worry about this, though, so don't worry until it becomes a problem (ie. when you have 100s or 1000s if kilobytes of styles).

Big development teams can't handle a single CSS style sheet?

I am currently in a 5-7 large development team creating a really large website with lots of pages and features.
I feel like we are in such a situation where a developer can change the style sheet to suit his own needs, but is unaware of the 1000 places where it probably change it for something else. I cannot blame him either, since I know it's hard to check everything.
It's a total mess.
I know that using one single style sheet file saves bandwidth and prevents duplicated code and maintenance, but I cant help wondering - is using style sheets a good idea for big sites, or should it be more object/element oriented.
Let's say you forget about the crazy large CSS and you define the CSS on each element instead. So each time you render a GreenBuyButton, it has the "style='bla bla bla'" on it. And this is pretty much done for all elements.
This will increase the bandwidth, but it will not create duplicated code.
Could this be a good idea or how does really large teams work on a single website do with CSS to avoid it being a mess?
Why don't you create multiple CSS sheets depending on the area of the site?
blog.css
accounts.css
shopping.css
Then you could have a serverside script (say PHP) combine all CSS into 1 sheet which will get you the same result of 1 small file (could use a minimizer as well).
Check your overall site with a CSS checker to find duplicates (css defined) and manage it that way.
Otherwise communication is key between your team, who develops what, and so people don't duplicate CSS definitions. A master CSS keeper would be best suited to manage the CSS styles, besides your team should have an agreed upon style and not go rouge creating their own unique styles.
My recommendation would be to use the CSS rules on specifity to help you. For each CSS that is not global, put an activate selector on, for example
.user-list .p {
font-size: 11pt
}
.login-screen .p {
font-size: 12pt
}
This will make it easy to identify what rules are for which pages, and which rules are global. That way developers can stick to their own set of styles, and no mess up anyone else's.
Change how you write CSS.
Instead fo treating every area of the website like a specific piece of markup that needs styling, start defining broad classes.
Enforce some rules. Like, "All <ul> have a specific look for this project." If there are multiple ways you want to style an element, start using classes. This will keep your website looking uniform throughout. Uniformity reduces broken layout.
Create building block classes like a "framework" of sorts. This has helped me so often that I never start a project without doing this first. Take a look at the jquery-ui themeroller framework to give you the idea. Here's an example:
.icon { display:block;width:16px;height:16px;}
.icon-green { background:url(/green.png);}
.icon-blue { background:url(/blue.png);}
Then on the elements:
<span class="icon icon-green"></span>
<span class="icon icon-blue"></span>
Breaking your styles up into their building blocks like this and using multiple classes on the element will keep your team members from having to change styles to suit their needs. If a particular styling quirk is not available they can define a new set of classes.
UPDATE:
Here is an example of how I used this method: Movingcost.com. Huge website, multiple different sections and pages, and only 252 lines of uncompressed css. Actually, these days I break things down further than I did on the movingcost project. I probably would have gone through those elements at the bottom of the stylesheet and figured out how to combine some of those into classes.
Multiple CSS files and combine in code
While doing development I found out that doing it the following way seems to be reasonable and well suited to development teams:
Don't put any styling into HTML. Maintainability as well as lots of head scratching why certain things don't display as expected will be really bad.
Have one (or few of them) global CSS that defines styles for global parts. Usually defines everything in template/master. Can be bound to master page or to generic controls used on majority of pages.
Have per-page/per-control CSS files when they are actually needed. Most of the pages won't need them, but developers can write them
Have these files well structured in folders
use naming and formatting guidelines so everyone will be able to write/read code
Write server side code taht will combine multiple CSS files into a single one to save bandwith.
You can as well automate some other tasks like auto adding per-page CSS files if they're named the same as pages themselves.
Doing it this way will make it easier to develop, since single CSS files will be easier to handle due to less content and you will have less code merging conflicts, because users will be working on separate functionality most of the time.
But there's not feasible way of automating CSS unit tests that would make sure that changing an existing CSS setting won't break other parts of your site.
My favorite override trick is to assign the id attribute on the <body> of each page. It's an easy way to make page specific changes without breaking out a separate stylesheet file.
You could have the following html
<body id="home">
<h1>Home</h1>
</body>
<body id="about">
<h1>About</h1>
</body>
And use the following css overrides
h1 {color: black}
#about h1 {color: green}
The home page gets the default css while the about gets overridden.
Using style sheets on large sites is an excellent idea. However, it only really works when you apply your team standards to the style. It makes sense to have a singular template controller that links your style sheet(s). It also makes sense to appoint someone on the team as "keeper of the style" who all changes to the style sheet should go through before making substantive changes.
Once the style standards are agreed upon and defined, then all of the controls in the site should implement the styles defined. This allows developers to get out of the business of coding to style and simply coding to the standard. Inputs are inputs, paragraphs are paragraphs, and floating divs are a headache.
The key is standardization within the team and compliance by all of the developers. I currently lead a team site that has upwards of 30 style sheets to control everything for layout, fonts, data display, popups, menu and custom controls. We do not have any of these issues because the developers very rarely need to edit the style sheet directly because the standards are clearly designed and published.
The answer is in the name. The reason it's called cascading style sheets is because multiple can be combined and there are decent rules defined on which one takes preference.
First of all, doing all your styling inline is a ridiculous idea. Not only will it waste bandwidth like nothing else, it will also result in inconsistency. Think about it for a while: why would changing a line of css 'break' another page? That indicates your css selectors are poorly chosen.
Here are my suggestions:
use one css file for the basic site look. This css file is written by people doing mainly design, and as a result the site has a consistent look. It defines the basic colors, layout and such.
use another css file per 'section'. For instance, a 'shopping' section will use components that are nowhere else on the site. Use that to define section-specific stuff
put page-specific styling directly in the page (in the header). If this section becomes too big, you're doing something wrong
put exceptional styling directly on the components. If you're doing the same thing three times, abstract it out and use a class instead.
choose your classes wisely and use the semantics for naming. 'selectedSalesItem' is good 'greenBold' is bad
if a developer changes a stylerule and it breaks the rest of the site, why did he need to change it? Either it's an exceptional thing for what he's working on (and should be inlined) or it was basically broken on the rest of the site as well, and should be fixed anyway.
If your css files become too big to handle, you can split them up and merge them server-side, if you want.
You don't want to define CSS for each element because if you ever need to make a change that affects many elements one day, say the looks of all the buttons or headers, you will be doing a lot of Search/Replace. And how to check if you forgot to update one rule to keep your site consistent?
Stephen touched on a very strong point in CSS. You can assign multiple classes to an element.
You should define some basic rules that "ordinary" developers can't touch. They will provide the consistency through the site.
Then developers can assign an extra class to personalize any property. I wouldn't assign more than two classes though: a global and a personalized.
Considering you already have this huge stylesheet in your hands, I'm not sure how you will pick which one of the 7 developers will have to sit down through a month and organize it. That is probably going to be hard part.
First off, you need to extract your website's default element styling and page structure into a separate stylesheet. That way people understand changing those rules affects the entire site's appearance/structure, not just the page they're working on.
Once you do that, all you really need to do is document / comment all of your code. A person is a lot less likely to write duplicate code in a well-documented stylesheet, and that is a fact.

Page-specific css rules - where to put them?

Often when I'm designing a site, I have a need for a specific style to apply to a specific element on a page and I'm absolutely certain it will only ever apply to that element on that page (such as an absolutely positioned button or something). I don't want to resort to inline styles, as I tend to agree with the philosophy that styles be kept separate from markup, so I find myself debating internally where to put the style definition.
I hate to define a specific class or ID in my base css file for a one-time use scenario, and I dread the idea of making page-specific .css files. For the current site I'm working on, I'm considering just putting the style definition at the top of the page in the head element. What would you do?
Look to see if there's a combination of classes which would give you the result that you want. You might also want to consider breaking up the CSS for that one element into a few classes that could be re-used on other elements. This would help minimize the CSS required for your site as a whole.
I would try to avoid page-specific CSS at the top the HTML files since that leaves your CSS fragmented in the event that you want to change the appearance of the site.
For CSS which is really, truely, never to be used on anything else, I would still resort to putting a #id rule in the site-wide CSS.
Since the CSS is linked in from a different file it allows the browsers to cache that file, which reduces your server bandwidth (very) slightly for future loads.
There are four basic cases:
style= attribute. This is the least maintainable but easiest to code. I personally consider use of style= to be a bug.
<style> element at the top of the page. This is slightly better than style= because it keeps the markup clean, however it wastes bandwidth and makes it harder to make sweeping CSS changes, because you can't look at the stylesheet(s) and know what rules exist.
page-specifc css: This lets you have the clean HTML and clean main CSS file. However, it means your client must download lots of little CSS files, which increases bandwidth and page loading latency. It is, however, very easy to maintain.
one big site-wide CSS: The main advantage of one big file is that it's only one thing to download. This is much more efficient in terms of bandwidth and latency.
If you have any server-side programming going on, you might be able to just dynamically combine multiple sheets from #3 to get the effect of #4.
I would recommend one big file, whether you actually maintain it as one file or generate the file through a build process or dynamically on the server. You can specify your selectors using page-specific IDs (always include one, just in case).
As for the answer that was accepted when I wrote this, I disagree with finding a "combination of classes that gives you the result you want". This sounds to me like the classes are identifying a visual style instead of a logical concept. Your classes should be something like "titlebox" and not "red". Then if you need to change the text colour on the user info page, you can say
#userInfoPage .titlebox h1 { color : red; }
Don't start applying classes all over the place because a class currently has a certain appearance that you want. You should put high-level concepts into your page, represented by HTML with classes, and then style those concepts, not the other way around.
I would set an id for a page like
<body id="specific-page"> or <html id="specific-page">
and make use of css override mechanism in the sitewide css file.
I think you should definitely expand the thought process to include some doubt for "page specific css". This should be a very very rare thing to have. I'd say go for the global style sheets anyway, but refactor your css / html in a way that pages don't have to have super-specific styling. And if in the end there's a few lines of page-specific markup in the global css, who cares. It's better to have it in a consistent place anyway.
Defining the style in the consuming page or inlineing your style are two sides of the same coin - in both cases you are using page bandwidth to get the style in there. I don't think one is necessarily better than the other.
I would advocate making an #Selector for it in your site-wide main stylesheet. The pollution is minimal and if you really have that many truly unique cases, you may want to rethink they way you mark-up your sites.
I would put them in a <style /> tag at the top of the page.
It's not worth it to load a page-specific CSS file for one or two specific rules. I would place it in tags in the head of the document. What I usually do is have my site-wide CSS file and then using comments, section it up based on the pages and apply specific rules there.
As you know style-sheet files are static files and cached at client. Also they can be compressed by web server. So putting them in an external file is my choice.
For that situation, I think putting the page-specific style information in the header is probably the best solution. Polluting your site-wide style sheet seems wrong, and I agree with your take on inline styles.
In that case I typically place it at the top of the page. I have a page definition framework in PHP that I use which carries local variables for each page, one of which is page-specific CSS styles.
Put it in the place you would look if you wanted to know where the style was defined.
For me, that's exactly the same place as I would place styles that were used 2 times, 5 times, or 170 times - I see no reason to exclude styles from the main stylesheet(s) based on number of uses.

Minimize CSS length holding style of given HTML constant

Suppose A.css styles B.html. What tools/techniques are there to programmatically reduce the size of A.css while holding its styling effects on B.html constant? Here are some techniques I would imagine such a tool using:
Remove redundancies in A.css. For example, if the same class is defined twice you can remove the second definition without affecting semantics. This seems pretty easy.
Remove style definitions that aren't used. Does A.css style any elements that don't appear in B.html? If so, remove them.
Combine styles where appropriate. If A.css defines styles for div.x and div.y and every div that happens to have class x also has class y, one could combine the class definitions in A.css.
A different strategy would be to have a tool that examines the computed styles of each element in a piece of styled HTML and spits out the minimal style sheet that would preserve the computed styles. Does something like this exist?
UPDATE
Let me explain how I got in this situation. The CSS file in question is for an email, and it was created by basically copying a similar CSS file that we used in an associated web page. Because the HTML in the email is a proper subset of the HTML in the web page from which the CSS came, some of the CSS in the email is superfluous.
Generally you just remove all unnecessary whitespace. Remember to keep the original as well, so you don't lose readability when editing the site later.
I think making sure css files are gzipped by the webserver is your biggest bandwidth saver.
"Does something like this exist?"
Of course. See the CSS Tidy tool.
I do not believe that it removes unused css, though. See Sitepoint's Dust Me Selectors for that.
Unless you have an usually large CSS file, I would opt for readability and modifiability of the CSS file rather than having a smaller CSS file. Since CSS files are static (for the most part), most browsers will do a really good job of caching them. While all your suggestions are good ones, combining things that are the same now for different document elements can wreak havoc in the future when you only want to change one of those items.
I'm not aware of tools to remove redundant styles, but if you want to reduce file size for performance reasons there are several minifing tools out there:
See:
The art of Scaling
A better CSS minifier
A good idea is to compress your css.
This isn't zip-style compressing, it's actually re-writing the CSS (aka minification).
Of course, you can use mod_gzip or mod_deflate as well.
OK, you don't want a small file for the KB (using gzip compression is more effective!) but to prune the obsolete styles, which indeed would improve maintenance.
I don't know if the ideal tool you want exists, but Firebug (an extension for Firefox) can tell you want are the CSS elements used by a given HTML element. Not automated, but still a precious tool.
You can also edit the live CSS, to see if removing a style element alters the HTML page.