CSS - Separation of Color and Position - css

I'm just wondering what others do in this respect:
Do you try to keep positional CSS (layout) separate from color/flavor CSS (color, background-color, background-images, font-size and family) ?
Use two stylesheets? Combine two stylesheets server-side? Abstraction layer for the CSS?
or you don't even try?
I know sometimes after working on the same web project for six months I can usually live with the positional CSS but end up wanting to change the colors/images.

I tend to keep all the CSS together, without separating "color styles" from "positional styles" or "layout styles". I find that when I often try to debug a specific "module" it's easier to have all the CSS rules applied to one selector, and not spread out over the style sheet.
However, I do suggest you read Creating Sexy Stylesheets over at thinkvitamin.com. One thing I do is list the rules in a certain order everytime, so I know within the declaration block where to find what I want.
More info at Jina Bolton's http://creatingsexystylesheets.com/

You'll find that in large-scale projects, layout and color/flavor CSS will (if you're smart about it) usually just happen to be separate. Firstly, if you're catching yourself setting color/font-size/font-family style rules over and over, you're wasting your time. Typically you should define your fonts in one place: the body tag. Any additional fonts should be defined in their respective tags... h1, h2, p, etc. In my opinion it's not good practice to give these tags positional directives; they should be placed inside a div that will be responsible for their layout. Same goes for color and font size. I think the only exception to the rule would typically be background stuff, which is especially true if you have lots of gradients and fancy things like that.
Really what it comes down to is planning; a well-planned project needs very few color/flavor style rules. So to answer your question, yes, I usually have a "Global.css" file that defines all of my fonts and colors for h1-h5, a, p, and any other tags that will contain text.
Edit:
Usually, since the projects I work in are fairly large-scale and have a number of different modules, we separate the styles with in a sort of hierarchy; this makes sense because of the way CSS works -- as long as you don't change the style-rules put into place at the "base" (or in our case, the global.css) somewhere down the line, the styles will stick. This helps because when we want to modify the font of our site, we simply change the font-family rule at the "body" tag, and it will propagate throughout the entire site.
So, our stylesheet layout works something like this:
Global.css (Fonts/Text/Primary font colors)
--> genericBase.css (basic page structures such as columns that are used throughout the site)
--> nav.css (left-hand nav and/or top nav bar)
--> formLayout.css (labels, inputs, fieldsets, any other form stuff)
-----> forums.css (individual modules' styles that may deviate a bit from the usual structures, or simply things specific to those pages)
-----> blogs.css
-----> messages.css (etc etc etc)
The arrows here are meant to imply the "order" of the files in the hierarchy. The longer the arrow, the further down in the style-sheet the rules these files contain would be, if we had put all of the styles into one file.
So you see, the whole idea is to start with very general styles and work your way down to the most specific. Remember that the order in which your CSS files load matters to the browser. You can use this to your advantage. The interesting thing is, by the time we get to our specific modules' css files, we have very few styles to write because most of the other important stuff has actually work itself out along the way.
So like I said, planning is vitally important. I've found that this methodology makes it easier to "debug" my styles, and I use almost no hacks at all, usually only for silly ie6 stuff.
Let me know if you need more information. I'm glad this is helpful to you.

I used to separate them but it was more difficult to maintain. The problem is that many "formatting" properties will have an effect on the layout and many "layout" properties may actually be design.
Some examples:
While "border" may be considered a "formatting" property, they do take some amount of space so you will need to adjust your layout when setting or removing borders.
"line-height" is tied to the font-size and may be considered a "formatting" property, but it has a huge influence on the size of your elements and how they vertically align each other.
Margins and paddings are sometimes needed for the layout and sometimes used just for formatting.
If you think hard about it, there are very few properties that actually are purely formatting or purely layout.
It's often easier to just keep everything in the same file and try to keep it clean by having your declarations orders, related properties grouped, etc.

I keep everything together in a single file and use the folders feature in CSSEdit to keep it organised. Web design company Viget have a blog post about this technique here.

I separated my layout and color styles recently, and I now have several css files, which i import as follows:
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<link rel="stylesheet" type="text/css" href="style-default.css" title="Default Style" media="screen" />
<link rel="alternate stylesheet" type="text/css" href="style-bw.css" title="Black and White" media="screen" />
All layout is in style.css, then colors are in style-default.css.
This way I have a standard style, but users also have the option to change the colors. This not only offers options for the user, but it makes it easy to make color changes without touching the layout (I tend to change my colors much more often).
In Firefox my color options show up in the view menu under "Page Style."

I've fallen into the pattern of separating my CSS out into the following:
Layout (headers, footers, logos - general chrome)
Typography (fonts, sizes, re-usable inline font styles)
Widgets
The latter category is generally made up of CSS code I re-use between projects, and usually gets split down itself into:
Forms (left-aligned, right-aligned, styles for required fields, etc)
Grids (2-col, 4-col, etc etc etc - about 20 or so varieties)
Hacks (IE/other CSS hacks)
Other stuff (AJAX widgets, toolbars, comment boxes, etc - anything re-usable)
For colours, I just keep a cheat-sheet text file around. Keeping them in a separate stylesheet will probably only work if you are very, very disciplined.

I have started to use classes to handle colors specifically.
.element{margin, padding, layout stuff}
.ourcolor{#some color}
It lengthens the class attribute though:
< div class="element ourcolor" >
However, I can reuse the color:
< span class="ourcolor" >Some text
So far I prefer it as adjusting colors is much easier.

As Mark W pointed out, Creating Sexy Stylesheets is a fantastic read. One thing they do advocate is separating the styling concerns through a framework:
screen.css - A screen CSS file can either have all your styles you want to be used for on screen, and/or can import additional styles, such as the following:
reset.css - A reset CSS file can be used to “reset” all the default browser styling, which can help make it easier to achieve cross-browser compatibility.
typography.css - A typography CSS file can define your typefaces, sizes, leading, kerning, and possibly even color.
grid.css - A grid CSS file can have your layout structure (and act as the wireframe of your site, by defining the basic header, footer, and column set up).
print.css - A print CSS file would include your styles you want to be used when the page is printed.
If you follow this pattern, the colors would go in your typography.css, and layout would be in your grid.css.

I keep everything in one file and only provide different files for alternative styles (e.g. for printing).
Within that file I keep the overall layout (columns, headeer & footer) seperate from the actual contents (paragraphs, headings, lists...)
I am used to thinking object oriented, so I group the styles for different objects (menus, blog posts) together. From that perspective, colour and position both belong to the same object and therefore are kept together.
I am wishing for the ability to define colours once in a style sheet, assign them a declarative name (e.g. 'HeadingColour') and then use the name when assigning the colour to a selector...

Related

Maintaining print CSS stylesheet files

How do you usually handle changes to screen and print CSS files? I typically have one screen CSS and one print CSS file and for the most part the I would copy the contents of screen CSS to print CSS file and then modify some properties, classes or ids, maybe set some display:none to certain classes etc.
The problem is, while working on a site or web app I make numerous changes to screen CSS and usually forget about print CSS then I have to sync them from time to time and I just don't think that the most optimal way.
For print stylesheets I tend to also apply the media="screen" stylesheet to the media="print" as well as a second stylesheet that appears later, which essentially, just removes the elements I don't want to print.
It's a fairly simplistic approach, though, and only works to any potential if it's regularly reviewed, so I couple it with a policy of always revising (or, at least, checking) it when I revise the screen-stylesheet.

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'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.

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.

How far should you break up stylesheets?

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.

Resources