How far should you break up stylesheets? - css

I'm building a new site for my company, and I'm at the stage where I've created the html mockup of the first page. I'm going to use this as a basis for the rest of the site. I'm thinking of organising my stylesheet better now I've got the design looking consistent cross-browser, but I'm wondering how far to go when I'm breaking it up.
One idea is to have the following:
reset.css
typography.css
layout.css
colors.css
but where do I draw the line? theoretically I could go on and break them down into classes, ids etc, but I think thats going overboard.
Does this seem a reasonable method?

Coincidentally, A List Apart had an article covering this today. They recommend separating out into a few main categories, including some you listed (type, layout, color), but going further to include various tricks to keep older browsers happy.
On the other hand, keeping everything in one css file keeps the requests between browser & server down. A compromise might be to keep things separate for development, and merging for production (as a part of your build process, naturally :p).

I don't tend to split typography into a seperate stylesheet, although it seems like a good idea. I'd keep colours with typography though. My typical way is to have the following structure:
base.css
Global style used throughout the site
Aims to be extendable, for example so that it can be reskinned (but using the exisiting layout) for a microsite.
Implements/imports reset.css
page.css
Implements any page-specific changes.
microsite_skin.css
See base.css point 2

Pickledegg,
There's nothing wrong with breaking up style sheets. In fact, I find it very useful to organize css rules into different files based on their type, or what parts of the site they are applied to. If you lump rules into one large file, it can quickly become a mess and become very difficult to manage.
I would recommend coming up with your own scheme for separating your rules into files, and stick with it for all your projects.

I would break layout down into 2+ more parts, Base layout, IE Hacks, Menus (one for each menu area. This could be something like a top menu and a side menu)
If the site where to change color depending on the area I'd add one for each color area as well.
You also could use Yaml or similar as a base framework for your layout.
I'd keep the different stylesheets seperate while designing only merging them into 2-4 depending on the site shortly before uploading/releasing. always keeping the Hacks apart.

Separate them based on what you estimate your needs are going to be later on. If you think the typography, layout, or colours (globally) are going to change, then it's probably wise to at least delineate styles in that way so it's easier to replace one stylesheet with another later on.
But if you go too far in this you'll end up with duplicate rules everywhere (eg. #content having a font-family rule in typography.css, a color rule in colors.css, etc). That's not a logical way to split things up unless you anticipate the key changes to be taking place there.
If, on the other hand, like most sites the graphic design is going to remain fairly static but the architecture is going to have some changes made (eg a new content type) then you want to be grouping your styles based on the context of the site. For instance, article.css, search.css, etc.
Essentially, try to look ahead at what changes are going to be needed later on and then try to anticipate those changes in your css file setup.

The major problem IMO, is the duplicate property definition issue. This makes style-sheets unmanageable. To bypass this issue the divide and conquer approach is used. If we can ensure manageable style sheets with non-conflicting rules, then merging sheets or modularising them would be easy.
During reviews all I do is check for rule conflicts, classitis and divitis. Using Firebug/CSSTidy combination, the problem areas are highlighted. Thinking in these lines, I don't even look into typography and font-separation.
The goal is to have a singel base CSS file and separate browser hacks files. Multiple base CSS files would be needed if an application has different themes.

I put all styles, including IE6-and-7-specific styles, in one sheet. The IE6 and 7 styles are targeted using conditionally-commented divs that only appear if one of those browsers come to the site, e.g.:
<body>
<!--[if IE 7]><div class="IE IE7"><![endif]-->
<!--[if IE 6]><div class="IE IE6"><![endif]-->
... rest of markup ...
<!--[if IE]></div><![endif]-->
</body>
Not sure what people think of this approach, but the extra markup is negligible, and being able to include IE6/7 styles next to main styles without the use of hacks... just prepending the selector with ".IE" or ".IE6" etc, is a big convenience.
As for multiple stylesheets... save your HTTP requests. Use image sprites, one stylesheet, one "application.js" javascript, etc.
I'd still include separate sheets for the print and handheld styles, but that's about it...

Don't go too much further than that. If you do have to, try and find a way to merge them before production. The biggest issue is that you begin stacking up HTTP requests. It's not so much an issue for the browser but the amount of requests that need to be made for each page. I would say you are at a good point, more than 4 would be going somewhat overboard. Remember you can always use good commenting and formatting to break up large CSS files.

Whenever I'm trying to decide how far to break apart some files (I usually do this with code modules, but I apply the same principals to my css/js) I break it down to the smallest reusable files that make sense together. This isn't the best for the flow of data across the wire, but it makes maintainability of my source a lot easier. Especially if you're going to be having a lot of css floating around.
If you feel comfortable taking your colors.css and using the whole thing in another location without modification then you're probably fine.

Take a look at blueprint-css. Blueprint is a CSS framework which supplies a variety of default styles to you (such as browser reset code).
The style sheets in blueprint-css are organized as follows:
screen.css - default styles for screens
print.css - default styles for printing
ie.css - Internet Explorer specific fixes
application.css - contains the styles you write. Actually you shouldn't modify the previous three style sheets at all, because these are generated by blueprint-css. You can overwrite all blueprint-css styles in your application.css file.
For further details refer to the blueprint-css Git repository.

I break mine up almost exactly the same way:
reset.ccs - The standard reset from MeyerWeb
typography.css - Fonts, sizes, line-heights, etc
layout.css - All positioning, floats, alignments, etc.
colors.css (or more appropriately skin.css) - All colors, background images, etc.
These are then followed with IE-specific files included via conditional comments for the appropriate version.
I haven't had the need to separate them further, though I do organize each file in separate sections (base elements, named elements, classes, etc.)
UPDATE: I have changed my system a bit in the last few projects I have done.
base.css - Contains the CSS from the YUI reset and YUI base CSS files (with attribution)
main.css - Contains #import statements for the following:
typography.css - Fonts, sizes, line-heights, etc
layout.css - All positioning, floats, alignments, etc.
theme.css - All colors, background images, etc.
print.css - Overrides for the other CSS files to make the pages print-friendly.
I also then use conditional comments to add any IE-specific CSS files if needed.
My next step in improving this would be to add a build-process step to combine all of the CSS files into one file to reduce the HTTP requests on the server.

Everybody recommends to break. I'll be the devil's advocate.
How about NOT breaking style sheets. At least for production purposes is better to have a single request instead of many. The browser can process 2 simultaneous HTTP requests. This means that other 2 requests can be made after the first 2 are completed.
Combined files are a way to reduce the number of HTTP requests by combining all scripts into a single script, and similarly combining all CSS into a single stylesheet. Combining files is more challenging when the scripts and stylesheets vary from page to page, but making this part of your release process improves response times.
Yahoo and Google recommend this.
Google is recommending creating 2 files. One for everything necessary at the startup and 1 for everything else.
I think that even designers have to think in optimizing terms, not only hardcore developers.

Related

To put or not to put styles in css file?

I have a few lines of styles in every page. I'd rather not to put them in one css file for it might affect the styles of other page.
Do we really need to put the styles on a css file or is it ok to have
<style>...</style>
on every page?
What are the advantages of putting the styles in one page regarding to it's speed?
Does it speed up the loading of a page?
Basically it is a compromise option. Like Marty Wallace and Marc B stated.
The speed aspect is therefore a consequence of the option you take, as they are both valid. Just remember these two factors:
should you choose to use the CSS in the <style> section of your HTML file, it will be loaded everytime with each page load. Therefore, the more CSS rules you have in this section, the bigger the file, hence, longer loading time and slower speed.
If you <link> a stylesheet, that file will be requested everytime you load the page as well. So more or less the same relation to loading time is implied, although it may differ a lot in absolute value.
Also, you should have in mind that most browsers have caching mechanisms to optimize the usage of CSS. Try to read more about it so you can take advantage of it as well.
My opinion is that a mixed approach is probably the best option. Choose the rules that are to be applied to the common elements between your different pages and put them in a linked CSS file. Then, use the <style> tag to set specific CSS for elements on that page. This is my I-don't-care-about-it-that-much way of doing it.
Most of the time I found that CSS doesn't impact performance that much - but of course, it depends a lot on how much CSS you are actually using.

How do I refactor my CSS? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Manage CSS Explosion
I intended to build my web site with consistent styles and a coherent CSS scheme. But styles have crept out of control as I fine-tune individual pages (especially the main search form).
I've already gone through the process one time of breaking down the styles and rebuilding almost from scratch, and now it looks like time to do that again. How can I be efficient about this? I'm looking for a methodology, not a software utility (though I'm open to suggestions there...unless they cost money...).
Added note: I'm using a CSS framework and it's difficult to keep padding and margin coordinated.
Added note 2: The initial responses to this post are about best practices for CSS. Let's assume I already tried to follow best practices (in fact, I did). Now it's the clean-up procedure I'm looking for.
Added note 3: As of 14 June, combining this response (which I just found) with my post below is possibly a comprehensive answer.
Closure notes:
I learned my question is too general, and for that reason I wish I hadn't posted it. (Maybe that's why it got a down-vote ... I'll never know without a comment to explain the reason.) On the other hand I got just what I needed, so I'm happy I did post it.
I'm surprised I didn't get an up-vote for my answer -- even with the priceless input by others, I think it stands up pretty well.
My acceptance is going to be based largely on the usability of the answer, from my point of view -- a point of view that is sadly unable to digest some of the more exciting and comprehensive responses.
Closed as an Exact Duplicate
I just tried posting this again (subject, body, tags) to see if SO would suggest the post "How to Manage CSS Explosion". Interestingly, it did not. I added the tag refactoring to that post.
Split your css into separate files.
Put in one file the CSS reset (if you use one)
Then create a global.css file where you will put global styles that
apply to many-all pages
Then create individual files for your individual pages
Then start styling your pages. Every time you find a style rule that is reusable on many pages make it a CSS class and put it in the global.css file. Avoid using css ID's. You will find that you more often reuse things or will reuse in the future. In this case you use of course CSS classes.
Eventually you will find out that in your global.css you will find mostly CSS classes rules and html tag rules.
In your individual page CSS files you will find specific styles for each page.
That should give you a good first level of organization in your CSS. You can try to keep this separation through the whole development process, and for releases merge the CSS files into one and minify it.
my 2p worth about css cleanup, from a a previous similar question:
Tips for cleaning and maintaining a big css file
hope that this may help you together with others' answers!
start branching the project (here I suppose that you are using a version control tool) - that will allow you to play independently with the code and tag any milestone you will reach.
format your CSS with a beautifier - it will increase readability and will help searching for specific declarations without missing any instances.
try to identify unused / redundant css and get rid of it.
you could try to make your selectors shorter (e.g. .main .foo .bar might be fine as .bar) - it will improve readability and increase the performance, but take this with a pinch of salt and be ready to go back if things start to break at every step you take.
try to eliminate, if possible, any !important - make the selector more specific if needed. A css reset could help with that if most of the !important statements were made to fix browser-specific issues, otherwise introducing a css reset now could potentially add more problems than solve them - this, if there is no css reset in your app at all.
break and regroup the css into different modules (and files if that helps) - Object Oriented CSS is a possible technique to keep things more maintainable, it works best if you start with it but it may also help you in refactoring. https://github.com/stubbornella/oocss/wiki is a valid one but there are alternatives that you can consider, like SMACSS.
After that , you may consider using a css preprocessor such as Less or Sass, allowing you to define variables and mixins (similar to functions), modularity and much more - this may end up being a very expensive task though, so evaluate carefully if this will bring you more benefits than pain.
test as much and as often as you can, consider unit tests to make sure that any changes you make don't break anything somewhere else.
Sometimes re-writing everything may end to be less time consuming than refactoring, so don't be afraid to leave things as they are if your assessment will show that refactoring will not bring enough benefits.
EDIT
Things change and evolve for good; with regards to OOCSS/SMACSS approach, I have been happily following for a while, Yandex's BEM methodology for CSS, I would like to add it as an additional recommendation to the above
The first thing I'll do is separate the CSS based on the purpose. Maybe first the general page layout (DIVs, boxes, ...), then the styling (fonts, H1/H2/.../Hn titles), then some more specialized CSS (CSS for tables, for forms, for specific components of the site).
Such a separation helps to organize the changes; if you have to change or add a font, you know you'll find it in the styling section.
If you have to change the page layout, there goes the same, and so on.
Things tend to get messy when you have "individual pages"; is their layout so different?
You probably have to abstract the common features of the pages (for example, a main content container box) as long as you can.
Then think about specializing more the layout (1-column, 2-column) and so on.
If you have a programmer background, just think about classes and inheritance, the concept - yes I know it's a totally different domain... - but the concept can be useful in designing your css.
Based on this current round of work, here is what I've got so far:
the Planning
Have a system for handling To-Do notations in your HTML and CSS. Many IDEs support this directly, or a global search function will do just fine. Besides tagging issues, you want to note priority and perhaps even functional area (but keep it simple, not a burden).
Don't start revising your code. Use your To-Do system to plan first.
Make a concise list of your overall goals.
Consider overall sylistic changes such as color or font scheme.
Review best practices for CSS. Identify areas where your approach is ineffective, or where a good approach can be applied more consistently. Examples:
Consolidate classes
Eliminate haphazard use of in-line styles
Remove styles that are unused or redundant or conflicting
Improve general consistency; apply a set of conventions
Improve units of measure
Use class and id names that reflect content rather than format
Decide how much of the browser market you want to support and how much to embrace or rely on the newest standards.
Decide if there are any new approaches you want to adopt. Examples:
Use of a reset style sheet to standardize browser presentation
Use of a CSS framework
Use of a specialized library, for example to help with forms
Dynamic CSS (I recently followed advice to use PHP to handle my CSS, so I could dynamically control my color scheme. But I returned to straight CSS, because I like the presentation of CSS code in my IDE and the hybrid method messed that up.)
Review your list of goals and decide which should be pursued now. Any large-scale change should be treated as separate, if possible. If your column layout is a mess, it's not the time to learn how CSS can elegantly replace your javascript. The same goes for best practices, stylistic changes, etc.
If you have your CSS files configured for speed (for example, compacted footprint or all CSS in a single file), change that. Break the code into a human-managable format. Later when you're finished, try benchmarking to see if the more legible version is also efficient enough for production use.
Submit your CSS to a validator. Note any violations you want to fix.
Find instances of in-line styles in your HTML (search for the style attribute). Note any that should be moved to a style sheet.
the Work
Follow your To Do manager. Make common-sense back-ups. As you go, test your work on several browsers.
If you are into regular expressions, be warned: regex is often not effective or safe for rewriting CSS. (Not as hazardous as for HTML, but still). Regex may be useful sending CSS changes into the HTML, but again be careful.
If you have a lot of tweaks to margins and padding, try globally resetting all of them to 0px (okay, use regex here). Then systematically build them back up. You can resolve a lot of confusions this way. Of course, don't include any library or framework style sheets in this process.
Again, submit your CSS to a validator.
I see people has already suggested using approaches like OOCSS etc., so I'm going to offer a different/additional line of thought. I believe that the problem lie deeper than within your CSS and the way you write it. I believe the reason your CSS gets out of hand is this quote from your question:
... as I fine-tune individual pages ...
That makes me think that the problem much lie within your design, rather than you CSS, so let me elaborate a little bit on that. In my opinion a great design is a design that doesn't have to be customized for each individual page - and there are several reasons for that. The main reason is, as you've mentioned yourself, your CSS get out of control. Small tweaks and fixes on individual elements, depending on where they are placed, often leads to a mess that is a pain to maintain and work with. There is also a usability-reason in play here. I believe a UI becomes easier to use if the user is familiar with the UI and recognize herself from page to page, without to much variation. Of course you could have some element that isn't present on each page, or that vary somewhat between pages, but I always strive to keep them at a minimum.
My suggestion is therefor that if you intend to rewrite your CSS, which is time-consuming and hard work anyway, then why not go over and re-evaluate your design at the same time. You will probably find that there are elements that you can modify so that they look the same. Make it a goal to get rid of as many UI-elements as possible, without compromising the design. When you've unified the design as much as possible, then it is time to refactor your CSS, and maybe even your markup?
At this point, it might be better to get rid of all your CSS and start fresh. If you continue on your old code, it is easy to get lazy and get stuck with some of your old less efficient code.
For the coding, I believe the other answers contain lots of good recommendations and best practices. I would personally vote for OOCSS, a new discovery for myself as well, but it has improved the way I structure my CSS a lot. So have a look at that! That will also help you think in terms of reusing elements and the CSS for them, which goes a long way for simplyfing your CSS.
This answer is in regard to the note;
"I'm using a CSS framework and it's difficult to keep padding and margin coordinated." only.
Using a css pre-processor will solve this problem.
Because css has no way to assign inheritance and therefore we have to repeat 'margin:10px' over and over.
with a pre-processor you just do
#margin {10px}
#padding {10px}
then
.mySelector{
margin: #margin;
padding: #padding;
}
For the broader question rethink/simplify your design as your css is directly proportional to the complexity of the design and there is not much you can do about that.
See also, http://www.stubbornella.org/content/2011/04/28/our-best-practices-are-killing-us/
This is more advice about making your css maintainable than the Q of how to manage the process.
I create a bunch of separate css files each narrowly tailored to a specific attribute (colors, fonts, margins, corners) or feature (nav, form). Then I use a compile phase to combine and minify these files into one or more files to be sent to the client. I do this during my built/test process, but it could be done dynamically by a CGI script.
Before adopting a pre-compiler, consider the often-overlooked multiple-selector syntax:
element,
otherlement
{
margin:10px;
}
In this example, whenever I want an element to have a 10px margin, I add it to the list. I separate different sets of attributes this way - I may list the same element 5 times in my css - associating it with 5 different sets of attributes.
Also don't overlook adding various classes to the body tag to create OO-like inheritance - say you have 3 main sections of your site - assign the body tag a class based on those sections. Likewise, if you have 1000 product pages, you can give the body tag a class like "product485" and then create styles that apply just to that page. For example:
h1 {
margin: 10px;
}
.product485 h1,
.product484 h1
{
margin: 5px;
}
.contact h1 {
margin: 15px;
}
This might all be in a file called "margins.css" which specifies only margins.

Is it always bad idea to use inline css for used-once property?

I have a table, with 10 columns. I want to control the width of each column.
Each column is unique, right now I create an external CSS style for each column:
div#my-page table#members th.name-col
{ width: 40px; }
I know there is a best practice to avoid inline style.
I do approve using external CSS for anything look'n'feel related: fonts, colors, images.
But is it really better to use external CSS in this case?
It does not incur extra maintenance cost.
It is easier to produce.
Cons I can think of:
If you have separate designers and development team - using inline styles will force designers to modify content-file (aspx in my case).
It might use more bandwidth.
Anything else I've missed?
IMPORTANT: I am asking about only one specific case where style used will ever apply to exactly one element, and is not part of the global-theme, such as width of one particular column.
There are lots of reasons why style="" is bad. I consider it a bug anywhere I encounter it in my codebase. Here are some reasons:
style= has higher priority than other CSS selectors making it hard to effect changes in the stylesheet; the stylesheet has to work harder to override these.
style= rules are hard to find in the code when you need to make global changes.
You download this CSS code with every page view.
If you have multiple stylesheets for the same HTML codebase your style= rules are not part of the stylesheet and thus are unchangeable.
However, if you are generating content and it's difficult to describe this content in a static CSS file, you might also need to generate the CSS to match that content. It is often easier to simply generate style= rules despite the drawbacks. If, however, your generated content can be easily described in a CSS file, because the generated structure doesn't often change, or because you can easily generate HTML AND a CSS file at the same time, then it's probably better to not use style=.
Some suggestions for alternatives to style= that may be appropriate:
Instead of inline styles, use class names. Works well if you have lots of columns in your table that have the same properties, and which you expect to always have the same properties. Then your stylesheet can remain fixed while your HTML is fluid, since the CSS only references classes. This is probably the approach I'd use.
Use JQuery or some other javascript library to style your objects programmatically after the page loads.
Easier to produce is not really a valid argument - people like splitting huge chunks of code into smaller chunks - same with code and markup.
However:
+ No extra HTTP connection (unless you are already downloading a .css file anyway)
- Every time the page gets sent, this CSS is sent with => more bandwith
- Designers need to modify CSS in Application Code (bad practice)
Usually, you shouldn't - unless it's a really well thought through performance tweak as google does.

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.

What is the point of #import?

Can someone explain what are the benefits of using the #import syntax comparing to just including css using the standard link method?
As the answerer said, it lets you split your CSS into multiple files whilst only linking to one in the browser.
That said, it's still wasteful to have multiple CSS files downloading on high-traffic websites. Our build script actually "compiles" our CSS when building in release mode by doing the following:
All CSS files are minified (extra whitespace and comments removed)
We have a "core.css" file that's just a list of #import statements; during compilation, each of these is replaced by the minified CSS of that file
Thus we end up with a single, minified CSS file in production, whilst in development mode we have the separate files to make debugging easier.
If you use <link>s in your HTML files, all those files have to keep track of all the CSS files. This obviously makes changes and additions (both for CSS and HTML files) harder.
Using #import, you reduce a theoretically infinite number of changes down to one.
#import allows you have an extensible styesheet without having to change the html. You can link once to your main sheet and then if you want to add or remove additional sheets your html doesn't change.
Also, more smaller files help the browser do better caching. If you make a change in one part of a large sheet, the entire sheet must be downloaded again for every user. If the styles are separated into logical areas among a few sheets, only the file containing the part that changed needs to be downloaded. Of course, this comes at the cost of additional http requests.
One other handy bit, although pretty outdated, is that Netscape 4 couldn't handle #import, so it is a good way of serving a stylesheet to NS4, then having another stylesheet for more modern browsers that was imported in a standards compliant way.
#import is CSS code. <link> is HTML code. So, if you want to include stylesheets in other stylesheets (or if you can’t change HTML), #import is the way to go.
According to the CSS spec, all #import declarations must appear before any style rules in your stylesheet. In other words, all at the top of your stylesheet
Any #import declarations that appear after style rules should be ignored. Internet Explorer has never respected this; I believe other browsers do. This makes #import a bit less useful, because rules in a stylesheet that’s imported will be overriden by rules of equal specificity in the importing stylesheet.
It allows you to keep your logic CSS file spread over multiple physical files. Helps in team development, for example. Also useful when you have a lot of CSS files that you want to separate by functional areas (one for grids, one for lists, etc), let have accessible in the same logical file.
Say you work for Massive Dynamics, Corp.. It has a Widgets division. The Widgets division has an Accounts department. Accounts is divided into Accounts Payable and Accounts Receivable.
Using #include, you start the website with one top-level global.css stylesheet, which applies to everything.
Then you create a second stylesheet, widgets.css for the Widgets division. It #includes the global one, and its own styles (which can over-ride the global styles if needed, because of the Cascade). Then you create a third accounts.css for Accounts. It #includes widgets.css, which means it also includes global.css. Lather, rinse, repeat.

Resources