CSS Best Practices for Large Scale Web Site - css

So far, my experience in web design has been with very small scale sites and blogs (where there isn't much diversity in page styling). However, I am now beginning to tackle some significantly larger scale web sites and I want to start off on the right foot by creating a scalable and maintainable css file / structure.
Currently, my method for applying styles to web pages is to give every web page a distinct ID in the body, and then when I'm designing a page my css rule will look like this:
body#news section .top { rules }
Surely there is a more maintainable approach to applying CSS for a large-scale web site?

Avoid giving each page a body tag with a unique ID. Why? Because if a page needs to be styled uniquely, it should have its own stylesheet.
I will often have a main.css stylesheet, stylesheets for various similar portions of my website (like an administration.css for an admin section, assuming the pages in the admin section shared a similar look and feel), and then give certain unique pages their own stylesheets (like signup.css).
I then include the stylesheets in order from least-to-most specific, because if two otherwise-identical rules are encountered, the rule in the most "recently" included stylesheet will be used.
For example, if my main.css had:
a { color: red; }
... and for some reason, I wanted my signup page to have blue links:
a { color: blue; }
The second rule will overwrite the first if my signup.css were included after main.css.
<link rel="stylesheet" href="/stylesheets/main.css">
<link rel="stylesheet" href="/stylesheets/signup.css">

there is a very informative and detailed answer over here: Managing CSS Explosion
you could also check out object oriented css: http://www.slideshare.net/stubbornella/object-oriented-css
or css systems: http://www.slideshare.net/nataliedowne/css-systems-presentation

To sum up the above answers and give some additional comments:
You put everything in one CSS, and use unique body IDs for page-specific settings. This approach speeds up your site because you're saving HTTP requests (browser caches just one file)
You have one CSS per page, plus one global one to take care of global settings, header, footer and any other elements that appear everywhere. This is friendlier if you have more than one developer working - less chance of conflicts because of updates to the same file. Even if you use a versioning system like SVN (and with a big site you should), it's always safer to have different files.
You can have the best of both worlds by separating into files, and then using a minifier to merge and compress all of them into one "compiled" CSS. This is more complicated, you need to fit it into your workflow, and it makes frontend debugging harder. See Any recommendations for a CSS minifier?.

What you should find is that most pages will have similar design aspects like typography and basic formatting which means you dont need to apply and id to the body tag.
You should try and use ids that describe the structure of your page (header, footer, sidebar etc) which can be reused on each page where neccessary. Only when styling areas specific to news or project etc is when you should start using id=news.
At the end of the day there is no right and wrong answer. Just try to maintain resuable css styles whilst trying not to overload your markup with uneccessary tags.

Always use classes for CSS. This will allow you to reuse more of your code. Since you can have multiple duplicate classes per page this allows you to really create some small code.
CSS parses from right to left. So in the example above it will find your selector in this order:
elements with the classname .top
elements with the classname .top that are in the section tag
elements with the classname .top that are in a section tag also contained in the #news element
...etc.
Look at it this way you should really try to keep your selectors as short as possible. Create a base style for .top, then if you need to write something custom for the #news section you can use #news .top.
Always try to use the shortest possible rules.
margin:0 5px;
over
margin:0 5px 0 5px;
It's basic, but you'd be amazed at how many people don't do this.
Also learn what you can shorted:
ex: font:bold 12px Helvetica, Arial, sans-serif;
One thing that is very helpful is if you alphabetize your rules. Especially if you are using CSS3 -webkit- and -moz- properties. I get a lot of push back on this one, but I work with 12+ developers and I've seen
.myClass { color:#f00; /* more stuff */ color:#fff; }
If they are alphabetical then you'll avoid code duplication.

Related

How to remove CSS spaghetti in legacy web app?

After working on several large web applications, and seeing gigantic style sheets with no clear structure, I'd really love to know if people have found ways to keep their css clean for large and complicated web apps.
How do you move from a legacy, mess of css to cleaned up, nicely cascading, DRY stylesheets?
The app I'm currently working on has 12000 lines of css. It's grown to this size organically as early on there were no standards or review of the css, the only rule was to make the app match the design. Some of the problems we constantly have:
Conflicting styles: one developer adds a .header { font-weight: bold;} but .header was already used in other modules and shouldn't be bold in those.
Cascading problems: Foo widget has a .header but it also contains a list of Bar widgets with .header classes.
If we define .foo .header { ... } and .bar .header { ... } anything not explicitly overwritten in foo will show up in bar.
If we define .foo > .header and .bar > .header but later need to modify foo to wrap header in a div, our styles break.
Inheritance problems, we constantly redefine widget fonts to 11px/normal because some top container uses a 12px / 18 px line height.
Fighting against widget libraries, using libraries such as dojo/dijit or jquery ui that add tons of styles to be functional means that our code is littered with places where we have to override the library styles to get things looking just right. There are ~2000 lines of css just for tweaking the builtin dijit styles
We're at a point where we're thinking of implementing the following rules:
Namespace all new widget classes - if you have a widget foo all sub-classnames will be .foo_ so we get: .foo, .foo_header, .foo_content, .foo_footer. This makes our css essentially FLAT, but we see no other way to organize our code going forward without running into the legacy styles or the cascading problems I mentioned above.
Police generic styles - have a small handful of generic classes that are only to be applied in very specific situations. e.g. .editable - apply to portions of a sentence that should invoke an editor - should only contain text nodes.
Leverage css compiler mixins To avoid repeatedly defining the same styles in different widgets, define and use mixins. Although we worry the mixins will get out of control too.
How else can we move from css mess that constantly introduces regressions to something maintainable going forward.
We're using a style guide in the form of a simple HTML page with examples of every CSS rule in the stylesheet. It's very easy to tell if you add a new, incompatible rule since the examples are aligned on top of eachother.
An example I like: http://getbootstrap.com/components/ (added 2015)
The other pro you get from this method is reusability: you know what you got and you know that you want the style guide to be as small as possible - therefore: reuse.
When you make changes to styles already in use: check the style guide. If it doesn't change it's probably good (you might need to browse around a bit if you've just changed something including box model-issues, or width, height, padding, margin in general).
How do you move from a legacy, mess of
css to cleaned up, nicely cascading,
DRY stylesheets?
Use the style guide as a unit test. Once you got the essential parts in it: reduce, refactor and combine (you most probably will find some collissions between .campaign_1 span and your regular rules, inheritance can be your friend).
Conflicting styles: one developer adds
a .header { font-weight: bold;} but
.header was already used in other
modules and shouldn't be bold in
those.
In reply to Adriano Varoli Piazza's comment and the quote above: I don't recall this as a problem fully belonging to the CSS but more to the HTML markup. No matter what you do, it will be some heavy lifting. Decide which rule you'd want to keep and take actions towards cleaning out the lesser-used-ones; for example: via inheritance: #news a .header { ... } or renaming the HTML-class a .stand_out_header { ... }.
About the following idea
Namespace all new widget classes - if
you have a widget foo all
sub-classnames will be .foo_ so we
get: .foo, .foo_header, .foo_content,
.foo_footer. This makes our css
essentially FLAT, but we see no other
way to organize our code going forward
without running into the legacy styles
or the cascading problems I mentioned
above.
Use a containing element instead, which will be much more easy to maintain:
<div id="widget_email">
<h2>One type of h2</h2>
</div>
<div id="widget_twitter">
<h2>Another h2</h2>
</div>
I find that the method for "namespacing" and limiting conflict in CSS is separate into different includes what you want to apply, so each page calls only what it needs. Conflicting rules can then be made more specific simply by defining them in a more particular include:
general css for all pages
css for pages in section A
css for pages in section B
So if you find a .header modification you added in the general css works in A but doesn't in B, you simply move it to the lower CSS file.
Yes, this implies more files to load. There are ways around it with server-side languages, like reading all files with php and sending only one block of content.

What's so bad about in-line CSS?

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.
I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?
The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?
Example (is this bad?):
<img src="myimage.gif" style="float:right" />
Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like
<div style ="font-size:larger; text-align:center; font-weight:bold">
on each page to denote a page header, it would be a lot easier to maintain as
<div class="pageheader">
if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.
However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.
The advantage for having a different css file are
Easy to maintain your html page
Change to the Look and feel will be easy and you can have support for many themes on your pages.
Your css file will be cached on the browser side. So you will contribute a little on internet traffic by not loading some kbs of data every time a the page is refreshed or user navigates your site.
The html5 approach to fast css prototyping
or: <style> tags are no longer just for the head any more!
Hacking CSS
Let's say you're debugging, and want to modify your page-css, make a certain section only look better. Instead of creating your styles inline the quick and dirty and un-maintainable way, you can do what I do these days and take a staged approach.
No inline style attribute
Never create your css inline, by which I mean: <element style='color:red'> or even <img style='float:right'> It's very convenient, but doesn't reflect actual selector specificity in a real css file later, and if you keep it, you'll regret the maintenance load later.
Prototype with <style> instead
Where you would have used inline css, instead use in-page <style> elements. Try that out! It works fine in all browsers, so is great for testing, yet allows you to gracefully move such css out to your global css files whenever you want/need to! ( *just be aware that the selectors will only have page-level specificity, instead of site-level specificity, so be wary of being too general) Just as clean as in your css files:
<style>
.avatar-image{
float:right
}
.faq .warning{
color:crimson;
}
p{
border-left:thin medium blue;
// this general of a selector would be very bad, though.
// so be aware of what'll happen to general selectors if they go
// global
}
</style>
Refactoring other people's inline css
Sometimes you're not even the problem, and you're dealing with someone else's inline css, and you have to refactor it. This is another great use for the <style> in page, so that you can directly strip the inline css and immediate place it right on the page in classes or ids or selectors while you're refactoring. If you are careful enough with your selectors as you go, you can then move the final result to the global css file at the end with just a copy & paste.
It's a little hard to transfer every bit of css immediately to the global css file, but with in-page <style> elements, we now have alternatives.
In addition to other answers.... Internationalization.
Depending of the language of the content - you often need to adapt the styling of an element.
One obvious example would be right-to-left languages.
Let's say you used your code:
<img src="myimage.gif" style="float:right" />
Now say you want your website to support rtl languages - you would need:
<img src="myimage.gif" style="float:left" />
So now, if you want to support both languages, there's no way to assign a value to float using inline styling.
With CSS this is easily taken care of with the lang attribute
So you could do something like this:
img {
float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
float:left;
}
Demo
Inline CSS will always, always win in precedence over any linked-stylesheet CSS. This can cause enormous headache for you if and when you go and write a proper cascading stylesheet, and your properties aren't applying correctly.
It also hurts your application semantically: CSS is about separating presentation from markup. When you tangle the two together, things get much more difficult to understand and maintain. It's a similar principle as separating database code from your controller code on the server side of things.
Finally, imagine that you have 20 of those image tags. What happens when you decide that they should be floated left?
This only applies to handwritten code. If you generate code, I think that it's okay to use inline styles here and then, especially in cases where elements and controls need special treatment.
DRY is a good concept for handwritten code, but in machine-generated code, I opt for "Law of Demeter": "What belongs together, must stay together". It's easier to manipulate code that generates Style tags than to edit a global style a second time in a different and "remote" CSS file.
The answer to your question: it depends...
Using inline CSS is much harder to maintain.
For every property you want to change, using inline CSS requires you to look for the corresponding HTML code, instead of just looking inside clearly-defined and hopefully well-structured CSS files.
The whole point of CSS is to separate content from its presentation. So in your example you are mixing content with presentation and this may be "considered harmful".
In addition to the other answers, another concern is that it violates the recommended Content Security Policy from MDN, https://infosec.mozilla.org/guidelines/web_security#content-security-policy
The justification they use is that inline javascript is harmful, XSS, etc., but it doesn't justify why inline styles should also be disabled. Maybe someone can comment as to why, but until then, I'll just rely on appeal-to-authority and claim: it's a security best practice to avoid inline styles.
Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.
I think that even if you want to have a certain style for one element, you have to consider the possibility that you may want to apply the same style on the same element on different pages.
One day somebody may ask to change or add more stylistic changes to the same element on every page. If you had the styles defined in an external CSS file, you would only have to make changes there, and it would be reflected in the same element in all of the pages, thus saving you a headache. :-)
Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".
Using inline styles violates the Separation of Concerns principle, as you are effectively mixing markup and style in the same source file. It also, in most cases, violates the DRY (Don't Repeat Yourself) principle since they are only applicable to a single element, whereas a class can be applied to several of them (and even be extended through the magic of CSS rules!).
Furthermore, judicious use of classes is beneficial if your site contains scripting. For example, several popular JavaScript libs such as JQuery depend heavily on classes as selectors.
Finally, using classes adds additional clarity to your DOM, since you effectively have descriptors telling you what kind of element a given node in it is. For example:
<div class="header-row">It's a row!</div>
Is a lot more expressive than:
<div style="height: 80px; width: 100%;">It's...something?</div>
Inline CSS is good for machine-generated code, and can be fine when most visitors only browse one page on a site, but one thing it can't do is handle media queries to allow different looks for screens of different sizes. For that, you need to include the CSS either in an external style sheet or in an internal style tag.
In-page css is the in-thing at the moment because Google rates it as giving a better user experience than css loaded from a separate file. A possible solution is to put the css in a text file, load it on the fly with php, and output it into the document head. In the <head> section include this:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
Put the required css in styles/style1.txt and it'll get spat out in the <head> section of your document. This way, you'll have in-page css with the benefit of using a style template, style1.txt, which can be shared by any and all pages, allowing site-wide style changes to be made via only that one file. Furthermore, this method doesn't require the browser to request separate css files from the server (thus minimising retrieval / rendering time), since everything is delivered at once by php.
Having implemented this, individual one-time-only styles can be manually coded where needed.
According to the AMP HTML Specification it is necessary to put CSS in your HTML file (vs an external stylesheet) for performance purposes. This does not mean inline CSS but they do specify no external stylesheets.
An incomplete list of optimizations such a serving system might do is:
Replace image references with images sized to the viewer’s viewport.
Inline images that are visible above the fold.
Inline CSS variables.
Preload extended components.
Minify HTML and CSS.
Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.
So I will be the contrarian here and say that inline css is great and that people who scream at you for using it are just following what they have been told without actually giving it any original unbiased consideration.
Even though I totally agree with all the answers given above that writing CSS in a separate file is always better from code reusability, maintainability, better separation of concerns there are many scenarios where people prefer inline CSS in their production code -
The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.
In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS
We have created a template-driven artifact generator that provides an include file capability for any kind of text artifact -- HTML, XML, computer languages, unstructured text, DSV, etc. (E.g., it's great for handling common Web or manual page headers and footers without scripting.)
Once you have that and use it to provide "style" tags inside your "head" tag, the "separation of concerns" argument goes away, to be replaced by "we have to regenerate after every change to the template" and "we have to debug the template from what it generates". Those gripes have been around since the first computer language to get a preprocessor (or someone started using M4).
On balance, we think the meta-izing capability of either a CSS file or "style" tags is cleaner and less error-prone than element-level styling. But it does require some professional judgment, so newbies and scatterbrains don't bother.

If i can include css per page basis then should i mak different css file for each page if needed?

If i can include css per page basis then should i mak different css file for each page if needed other than reset css file?
i use eric meyer css reset code in main.css
Everything that is shared between multiple pages should go into a single CSS file.
If you have certain elements on only one page then it is ok to put this into an extra CSS file. This also prevents your main CSS file from getting to large.
Keep the following in mind: Don't repeat yourself. When you noticed that you put the same CSS configuration in two different CSS files, this is an indicator that this configuration should probably go into the main CSS file or both pages should at least use the same CSS file.
Edit:
You can give the elements that should share common settings the same class. E.g.
.foo {
color: green;
}
/* in this case, is the same as : */
#div1, #div2 {
color: green;
}
<div id="div1" class="foo">
</div>
<div id="div2" class="foo">
</div>
Also remember that elements can have more than one class, e.g. <div class="foo bar"></div>
Maybe a CSS introduction also helps.
A common solution is to put everything in one css file, with either small css files for parts that change or a class on body so you can write:
body.single #some:selector {
#css
}
body.blog #some:selector {
#css
}
As said before, don't repeat yourself!
Of course you can do this, but you should not, for two reasons (and more, which I can't think of right now):
You lose caching speed. While it's true that the page will be faster on first load (smaller CSS), each page needs to get its own CSS loaded. One CSS for all pages -- assuming it's not ridiculously huge -- lets the server cache and the client cache better. Mostly the latter is what we're trying to allow with one CSS.
Unless your site is truly beyond strange, you probably do NOT want to have different CSS for each page. A uniform look and feel demands a unified stylesheet.
As someone once told me on SO, "there are no absolutes, ever! :)" So while you might have a rare case that justifies many many CSS files, I recommend that you see if you can take advantage of unifying in one unless you have a good reason not to.
From your question it's not clear if you need help on using one stylesheet to address different elements on different pages. Generally, you can handle that by getting used to multiple classes, like:
<div class="one two three">
but CSS addressing is very flexible and you can do everything you want without having to use separate files. Unless you want to.

Multiple classes in body tag, multi-dimensional css structure or blueprint for insanity?

This question is about an approach to css structuring, and so is more discussion oriented.
I'm working with some outsourced css where the body tags have multiple classes assigned, up to half a dozen. (To make things a little worse, none of the css selectors include an html tag which is making it confusing to analyze the css.) These body classes are then used to modify classed or id'd widgets within.
It seems like this approach is like adding an additional dimension to the css, perhaps in some attempt to create a structured css approach. Documentation might have helped, had we been provided any.
This differs from my approach where widgets are styled primarily via id'd divs, perhaps extracting the more generic elements into a class, i.e. div#MyWidget.widgets.
Any ideas on whether such an approach is maintainable, especially considering I am dealing with websites with thousands of pages including tons of legacy stuff, all done by different people with different skill levels? Thanks...
I find nothing particularly wrong with this approach, provided you are conceptually using the body tags to apply very general style rules. The higher up the class is in the DOM, the more generic it should be.
It's hard to answer specifically without examples. One I frequently use is to turn the URL segments into classes for body tag in my pages, for relatively small sites:
// mysite.com/users/show/
<body class="users show">
<div id="Content">
...
</div>
</body>
I use this almost exclusively for overriding default styles on very specific pages:
#Content {
width:500px;
}
.users.show #Content {
width:600px;
}

What is a good CSS strategy? [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 7 years ago.
Improve this question
We have a large ASP.Net website that has a single css stylesheet which is getting out of control.
I am thinking of using the following strategy (taken from http://www.techrepublic.com/article/developing-a-css-strategy/5437796/) which seems logical to me...
you might have one CSS file devoted to sitewide styles and separate CSS files for identifiable subsets of site pages (such as pages for a specific department or pages with a different layout style). For styles that are unique to a specific page, use a separate CSS file for each page (if there are too many styles to fit comfortably in the document header). You link or import the appropriate CSS files for each page, so that you load all the styles needed to display that page, but very few unnecessary styles that only appear on other pages.
Is this a good way to proceed? What are the alternatives?
I think the best option is to divide css in:
-layout.css
-content.css
Then if you need other more specific you can add more like an css for the ads: ads.css, or one css for a specific section.
I would also add ie.css for IE css hacks.
I would not speak about creating one css for only one page: the problem you can have if you use too many css, is that your page will have to do more requests to the server and this will slow your page.
This is why i recommend you to implement an HttpHandler which will create a cache copy in only one file of the css you need at the moment. Look here:
http://blog.madskristensen.dk/post/Combine-multiple-stylesheets-at-runtime.aspx
There are three principle methods used for breaking up stylesheets: property-based, structure-based, and hybrid. Which method you choose should most be based on workflow and personal preference.
Property-Based
The most basic, representative form of a property-based breakup would be to use two stylesheets: structure.css and style.css. The structure.css file would contain rules that only used properties like height, width, margin, padding, float, position, etc. This would effectively contain the "building blocks" necessary to arrange the elements of the page the way you want. The style.css file would contain rules with properties like background, font, color, text-decoration, etc. This effectively acts as a skin for the structure created in the other stylesheet.
Additional separation might include using a typography.css file, where you'd place all of your font properties. Or a colors.css file, where you'd place all of your color and background properties. Try not to go overboard because this method quickly becomes more trouble than it's worth.
Structure-Based
The structure-based method of breaking up stylesheets revolves around segregating rules based on what elements to which they apply. For example, you might see a masthead.css file for everything in the header, a body.css file for everything in the content area of the page, a sidebar.css file for everything in the sidebar, and a footer.css file for everything at the bottom of the page.
This method really helps when you have a site with lots of distinct sections on each page. It also helps minimize the number of rules found in each stylesheet. Unlike the property-based method, which tends to have a rule in each stylesheet for each element on the page, with this method you only have one rule in one stylesheet for any given element.
Hybrid
As you might expect, the hybrid method combines the best of both methods and it's my preferred choice. Here you create a structure.css file, just like in the property-based method, using only those properties that you need to create the basic layout. Then you create additional stylesheets like masthead.css, which skins the header; body.css, which skins the content; etc.
Other Considerations
One problem that plagues each of these methods is that by creating multiple stylesheets, you require that the client's browser fetches many files. This can have a negative effect on the user experience because most browsers will only make two concurrent requests to the same server. If you have seven stylesheets, that means adding potentially hundreds of milliseconds on the initial page load (this effect is lessened once the stylesheets have been cached, but you want to make a good first impression on those new visitors). It's for this reason that the CSS sprites technique was created. Breaking up your stylesheets may wipe out any gains made by using sprites.
The way around this is to compress your broken-up stylesheets back into one stylesheet when the user makes a page request.
To get the best of both worlds, consider using a CSS meta-language like Sass. This allows a CSS author to break one stylesheet into many while still only presenting one stylesheet to the browser. This adds a step to the CSS authoring workflow (though it could potentially be scripted to compile the Sass into CSS any time a Sass file is updated), but it can be worthwhile, especially when considering some of Sass' many other benefits.
What you can do is have lots of easy to manage, separate files for development, then smoosh them all together into one file and minify it on your live site.
This is a little more work to set up, but gives you the best of both worlds - easy to manage site + fast page loads.
Edit: Yahoo's YUI compressor seems to be the best minifier around. It can compress both CSS and Javascript.
My solution, amidst plenty:
base.css / reset.css: your foundation {base layout, type, color} -- 100% reusability
helper.css: basic layout rules for modules as well as 'utility classes' {grid variations, forms, tables, etc} -- 90+% reusability
module.css: complex layout rules for modules {semantic modules like .post or .comment} - 75% reusability
layout.css: template-based rules {#hd, #bd, #ft, #homePage, etc.}- almost no reusability
color.css: all color rules, combined - 50% reusability
type.css: all type rules, combined - 75% reusability (text styling has less variations)
this separation also allows mobile and print versions for the layout sheets, all controlled by #import via the stylesheet I link to the html.
I am using this for a medium-sized site. For extra organization, I keep each sheet sectioned basically the same {wrapper, general, unique, etc}. I also tag my selectors and properties, as well as indent them in order of dependency inside the same selector group, so I know what rules I am referencing or extending. This framework allows nearly infinite expansion while keeping things organized, understandable, and reusable. I've had to refactor a 7000+ line master.css file a month ago, so this is a new system I am trying out. I've found that 100% content-semantic CSS isn't as scalable and easy to understand as a semantic/layout hybrid, since that's what CSS is used for anyway.
1.25-yr-later-edit: Another method which might be more relevant is to just use a good CSS text editor. I'm positive VS is crap for working with CSS, unless you happen upon some extensions. If you're on windows, give E Text Editor a shot, b/c it's a TextMate Windows port and has bundles designed for CSS and markup that give you much better syntax highlighting and autocompletion. What you then can do is organize, even a 8000-line stylesheet, into collapsible folds:
/** Start Module 1 */
[css]
/* End Module 1 **/
And use the symbol list to display for you a quick TOC on the fly with a query like Start or Module 1 It also indexes lines with /** these types of comments **/ (great for tagging areas) and all CSS selector chains. You should have no trouble working with single big files with E. Besides, unless you're progressively enhancing your CSS it's all going to get minified anyway. I would also make sure to indent your CSS to somewhat mimic the structure of DOM section it is referring to.
.container {}
.container .inner {}
.container .head {}
.container .inner.alt {}
Otherwise, I agree with the '1 Base CSS and 1 Page/Section CSS` method, though it entirely depends on your business requirements.
I would check out YUI CSS. Maybe not the answer you were looking for, but YUI CSS removes much of the hassle with different browsers etc...
Work out some simple rules that work for you (or your company).
Divide your CSS into separate files, such as:
layout.css
content.css
menu.css
typography.css
Decide what declarations will go in each file, for example, ensure:
font-weight, text-decoration, font-family
and
h1, h2, h3, h4, h5, h6, a, p, li
All reside in the typography CSS file. Decide what to do for edge cases, such as border properties on headers, padding and margins on text elemants (layout or typography).
If your sets of declarations are getting unwieldy, some people like to organise them alphabetically.
Indent your css, for example:
#logo h1 {text-indent: -9999px}
#logo h1 a {display: block; width: 200px; height: 98px; backround...}
Comment your CSS, including references to other files if other rule for that specific selector reside there.
If you do divide you CSS into separate files, consider consolidating and compressing them into one file as part of your build & deployment process.
Make sure every developer is well aware of your standard for CSS.
Also, somewhat relevant, I've just been made aware of a Firefox plugin for finding unnecessary selectors. It's called Dust-Me Selectors.
netadictos makes some good points and I would concur. It's easy to seek reasons for more Css but the benefits of keeping them lean are far greater in the longer term.
In addition, have you looked at using themes and skin files within asp.net? The combination of .css and .skin can dramatically reduce the overall size of your Css, which is marginally good for performance but very good for easier administration.
Some exceptions could be contained within the one css file but if things are radically different within the one then you may consider a separate css or even a separate site if they are that different. Obviously you might load different versions of the themes depending on which user it is. This is where you could have an explosion of Css files. That is, say you had a css for each page and then you wanted to have different for different clients on your site, then you'd be growing exponentially. This of course assumes you have this challenge.
I wonder the same thing with regards to JavaScript files. If your site is highly dependent on Ajax to the point where almost every page requires some kind of custom Javascript then were do you stick it all?
Best practices oftern spout not having javascript in the page but as external files (as with css). But if you have a .js file per page then things will slowly get out of hand.
I'm not sure about Windows equivalents, but on the Mac you can get CSSEdit, which allows you to add folders to CSS files and manage them like that. There's a good explanation of it in this article.
Global css files have caused me headaches before. CSS usually isn't namespaced, so if two different modules create a div with a class of "box", then the intent of one overwrites the other. Also, styles on the [a] tag, [p] tag and other basic tags (ie. styles not based on classes or id's) will wreck havoc on 3rd party controls as your global style sheet cascades onto an html component that was designed assuming no other css on the page. Inappropriate usage of text centering to center elements can lead to hard to debug global centering. So I favor multiple css files. I've seen css managers (http modules that merge css together at request time), but decided the extra http requests is well worth limiting the scope of the damage ill considered css can do to my application.
We use Ruby on Rails so we have a clear controller/action pair, we use this to reference both CSS classes and Javascript views.
Specifically, grab the name of the controller+action name and embed this as a ID in the view, put it on the body tag or your main content div.
<body id="users_list_body">
Where "users" is the name of the controller, "list" is the action. Then in your CSS you have rules likes
#users_list_body
So you can scope all of your specific CSS to that view. Of course, you also have more general CSS to handle overall styling. But having this ID defined more easily allows you to create specific CSS for individual pages (since a controller/action maps to a specific page).
You end up having rules like this
#users_list_body table
#users_list_body table thead
Do the same for Javascript. So in the footer of every page you take your same controller/action name pair and embed it in a function call
//javascript
if(V.views.users_list) { V.views.user_list(); }
Then in your external Javascript you have something like
V = {};
V.views = {};
V.views.user_list = function() {
//any code you want to run for the Users controller / List action..
//jQuery or something
$('#save_button').click({ ... });
}
with all of your Javascript code scoped to a specific function, it ends up being all encapsulated. You can then combine all of your Javascript files into one, compress it and then serve it up as one file and none of your logic will conflict. One page's JS will not conflict with any other page's JS because each page is scoped by its method name.
Whatever your choice is, avoid using the #import directive.
Makes the browser load stylesheets sequentially, hence slowing down loading and rendering for your page.
Here is what I do: I keep my stylesheets separate, somewhat along the lines of what others have suggested. However, I have a script that concatenates them together, minifies them, adds the headers, and then gzips them. The resulting file is then used as the stylesheet and if it goes beyond the expiration date, it automatically recompiles. I do this on a sitewide basis for all the common files and then also on a page specific basis for CSS that will only appear on that page. At the most, I will only ever have 2 CSS files called per page and they will be compressed, which minimizes download time and size and the number of page requests, but I will still have the benefit of separating them in whatever way makes sense to me. The same strategy can also be used for JavaScript.

Resources