I found this CSS minifier (http://www.lotterypost.com/css-compress.aspx). There is a section at the bottom of that page labelled "What does the CSS Compressor purposely NOT do?" There are four things, two of which I couldn't understand why they might be destructive:
Combining individual margin, padding, or border styles into a single property.
margin-top: 10px;
margin-right: 0;
margin-bottom: 8px;
margin-left: 30px;
Becomes
margin: 10px 0 8px 30px;
And combining styles for the same element that are specified in different style blocks.
#element {
margin: 0;
}
#element {
color: #000000;
}
Becomes
#element {
margin: 0;
color: #000000;
}
I think CSSTidy does both of these. Is the web page above correct? Are there situations where these types of minification might be a problem?
I'm the developer of the CSS Compressor that is the subject of this question (http://www.lotterypost.com/css-compress.aspx), so I'll elaborate with an example of how a compressor can break the CSS cascade if a tool aggressively re-writes it.
There are many ways of targeting elements in a style sheet, and because a CSS compressor does not have intimate knowledge of the page’s DOM structure, classes, ids, etc., there is no way for a compressor to know if an optimization that crosses bracketed definitions will break or not.
For example, a simple HTML structure:
<div class="normal centered">
<p>Hello world.</p>
</div>
And some CSS:
div.normal p {
margin: 10px 0 10px 0;
}
div.centered p {
margin: 10px auto;
}
div.normal p {
margin-bottom: 5px;
}
The uncompressed code would produce a centered paragraph with a 10px top margin and a 5px bottom margin.
If you run the CSS styles through the CSS Compressor, you'll get the following code, which maintains the order and cascade of the original uncompressed styles.
div.normal p{margin:10px 0}div.centered p{margin:10px auto}div.normal p{margin-bottom:5px}
Let's say you want to aggressively compress the styles further, by combining the margins of the two div.normal p definitions. They both have the exact same selector, and they appear to redundantly style the bottom margin.
There would be two ways to combine the margins: you can either combine the two margin definitions into the first (top) div.normal p style or combine them into the last (bottom) one. Let's try both ways.
If you combine the margins into the first (top) div.normal p style, you get this:
div.normal p{margin:10px 0 5px}div.centered p{margin:10px auto}
The result of combining the margins that way would result in the bottom margin being incorrectly set to 10px, because the "centered" class would override the bottom margin (because the "centered" style defintion now appears later in the cascade).
If you combine the margins into the last (bottom) div.normal p style, you get this:
div.centered p{margin:10px auto}div.normal p{margin:10px 0 5px}
The result of combining the margins that way would result in the paragraph no longer appearing as centered, because the bottom "p" definition would override the left and right margins of "auto" that are defined in the "centered" class.
So we can see that by combining style definitions that even have the exact same selector can cause some pretty bad problems.
Would you personally ever write code like this? Maybe or maybe not. Because of the various "weight" rules of the cascade, it is possible to fall into this type of code trap without ever realizing it.
Furthermore, given the fact that in today's Web pages, multiple CSS files are often combined into one file to hit the server with fewer downloads, it is easy to imagine the CSS Compressor royally screwing up the cascade by re-writing multiple style sheets (possibly written by different people) that are appended together into one file.
In fact, I wrote the CSS Compressor for this very scenario on my Web site, Lottery Post. Each Web page has many style sheets supporting various jQuery and other components, and the CSS Compressor is used to automatically compress all of those style sheets into one single download. All pages on the site have at least 10 different style sheets combined together, and most pages have more than that.
For example, if you look at the code behind the CSS Compressor page itself, you will find the main style sheet in the head that looks like this:
<link rel="stylesheet" href="http://lp.vg/css/d11019.0/j2HKnp0oKDOVoos8SA3Bpy3UHd7cAuftiXRBTKCt95r9plCnvTtBMU2BY2PoOQDEUlKCgDn83h16Tv4jbcCeZ(gupKbOQ9ko(TcspLAluwgBqrAjEhOyXvkhqHA(h5WFDypZDK2TIr(xEXVZtX7UANdFp6n1xfnxqIMR8awqGE)vrwUgY2hrCGNNTt1xV7R1LtCSfF46qdH1YQr2iA38r1SQjAgHze(9" />
The gobbledeegook in the URL is actually an encrypted string containing all the style sheets to combine on the server. The server compresses them and caches the result.
The space- and time-saving techniques on that one style sheet call include:
Combining many style sheets into one file/download by simply appending them all together
Compressing the combined style sheet using the CSS Compressor (without messing up the cascade!)
Using a different domain name (lp.vg) for the style sheet download, which improves the browser's ability to download in parallel
Using a very short domain name (lp.vg)
GZip compression is applied to the style sheet on the Web server
The version number of the style sheet is embedded into the URL (".../d11019.0/...") so that if any style is changed in any of the multiple style sheets, I can change the version number and the browser will never use the version it has cached. (Note that the version number should be part of the URL path, not in the query string, because some proxy servers do not look at the query string to determine if a page should be retrieved from cache.)
I hope this better explains things and is helpful to those looking to improve page performance!
-Todd
MORE INFO:
To add to the above, imagine if we take your color example, and combine style definitions with the same selectors.
Here are some uncompressed styles:
div.normal p {
margin: 10px 0 10px 0;
}
div.centered p {
margin: 10px auto;
color: blue;
}
div.normal p {
color: black;
}
The CSS Compressor produces the following output:
div.normal p{margin:10px 0}div.centered p{margin:10px auto;color:blue}div.normal p{color:#000}
If we were to apply aggressive combining of style definitions that have the same selector, we will get the following code.
Method 1, combining both into the first definition, would incorrectly make the text color blue:
div.normal p{margin:10px 0;color:#000}div.centered p{margin:10px auto;color:blue}
Method 2, combining both into the second definition, would incorrectly make the text left-aligned:
div.centered p{margin:10px auto;color:blue}div.normal p{margin:10px 0;color:#000}
The only time combining style definitions with the same selector is 100% error-free is when the definitions appear directly one after the other, but in every other case this technique risks corrupting the cascade of styles.
I couldn't imagine a case where any developer would write code in this manner (two style definitions with the exact same selector, one immediately after the other), so I concluded that the amount of effort required to code it, and the possibility of an additional point of failure in the compressor, was not worth it by a long-shot.
Frankly, I would be very concerned about a CSS compressor that combined styles from different definition blocks, because the cascade is a very fragile thing, and it is extremely easy to break the cascade.
The page has a section on 'reason not used' that describes why it doesn't do these two things.
And on top of that, I would assume it's not trying to do these things because it isn't a complete CSS parser/interpreter, and would start to bork stuff like CSS conditional blocks.
By 'destructive' I presume you mean 'the CSS does not work as expected'.
Combining long-hand rules such as your first example can be done without any ill effects at all.
In a plain old stylesheet with no media blocks or other fancy stuff, the second example will also not cause any problem.
The reason #2 is risky is because changing the order of rules, or folding rules together without taking the Cascade into account, can result in breakages.
Some CSS compressors can reorder rules alphabetically, or by selector type. These are very risky because moving rules around may break cascaded behavour the author created.
Minifiers like the YUI compressor don't do any of these, opting for safer strategies like removing whitespace, redundant semi-colons and zeros, and the like.
With more CSS containing media blocks and other CSS3 code it is likely that many of the current CSS compressors won't work correctly at all. Most do not have a proper lexer for parsing the code - they use context aware byte-by-byte (Tidy) or regexs (most of the rest) to process the code.
When selecting a compressor I would suggest finding something that will do it locally and is backed with good test suite so you can see what case are (and are not) handled correctly.
Related
I'm using SASS but actually my question applies also to plain old CSS.
So I have this class:
.some-icon {
background-image: url('data:image/png;base64, someBase64String');
}
So, now I have to use this icon at several places. I also need to write some additional css to place it correctly at the different places where it should appear. Since I don't want to duplicate this huge base64 string I'wonder which approach to use.
Either use SASS's extend syntax:
.use-case-a{
#extend .some-icon;
margin: 10px 0 0 0;
...
}
The compiled css would look like this:
.some-icon, .use-case-a {
background-image: url('data:image/png;base64, someBase64String');
}
.use-case-a{
margin: 10px 0 0 0;
...
}
Or should I just write:
.some-icon {
background-image: url('data:image/png;base64, someBase64String');
}
.use-case-a{
margin: 10px 0 0 0;
...
}
And then apply both classes some-icon and use-case-a on it?
I read that the first approach can drain performance:
https://github.com/nex3/sass/issues/12
But I also read that applying multiple classes hurt performance, too.
What is the recommended practice here?
I too had this question and after some research I found a post about CSS Rendering Speed - Grouping Selectors vs Properties on Forrst.
While the author compares the difference between grouping selectors vs properties in the CSS, I wanted to know if it were faster to apply styles using multiple classes on the elements… so I made a test, the author ran it, turns out it is faster to use multiple classes in your html:
1k 10k
Grouping Selectors layout time ~12ms ~110ms
Grouping Properties layout time ~12ms ~117ms
Object Oriented CSS layout time ~11ms ~112ms
Grouping Selectors DOM ready ~50ms ~405ms
Grouping Properties DOM ready ~64ms ~640ms
Object Oriented CSS DOM ready ~47ms ~349ms
Grouping Selectors file size 55kb 563kb
Grouping Properties file size 93kb 943kb
Object Oriented CSS file size 64kb 633kb
Additionally when you use more classes in the markup your code will be more readable, predictable, maintainable, scaleable, etc. When you read the following code, you know that this item is an icon and that it's also a checkmark icon.
<div class="icon icon-checkmark"></div>
This code also allows for easy selection of all "icon" elements with JavaScript.
Overloading the styles on a class will limit the ways in which you can use the class.
All said, since the actual browser render time delta is negligible, optimization at this level should be focused on saving developer time.
The answers here are quite sound too: CSS - Multiple vs Single class on an element
I know that in a stylesheet div#name and #name do the same thing. Personally I've taken to using div#name for most styling I do, with the reasoning that it's slightly faster, and means that I can identify HTML elements more easily by looking at the CSS.
However all of the big websites I seem to look at use #name over div#name (stack overflow included)
In fact I'm finding it very difficult to find many websites at all that use div#name over #name
Is there some advantage to doing #name that I'm missing? Are there any reasons to use it over div#name that I don't yet know about?
Since the div part of div#name is not required (because ID are unique per page), it makes for smaller CSS files to remove it. Smaller CSS files means faster HTTP requests and page load times.
And as NickC pointed out, lack of div allows one to change the HTML tag of the element without breaking the style rule.
Since ID's have to be unique on the page, most ID's you'd run into would only ever appear once in your style sheet, so it makes sense not to bother including what element it would appear on. Excluding it also saves a few characters in your style sheet, which for large sites which get visited millions and millions of times a day, saves quite a bit of bandwidth.
There is an advantage to including the element name in the case where a division with ID "name" might appear differently than a span with ID "name" (where it would show a division on one type of page and a span on another type of page). This is pretty rare though, and I've never personally run across a site that has done this. Usually they just use different ID's for them.
It's true that including the element name is faster, but the speed difference between including it and excluding it on an ID selector is very, very small. Much smaller than the bandwidth that the site is saving by excluding it.
a matter of code maintainability and readability.
when declaring element#foo the code-style becomes rigid - if one desires to change the document's structure, or replace element types, one would have to change the stylesheets as well.
if declaring #foo we'll better conform to the 'separation of concerns' and 'KISS' principals.
another important issue is the CSS files get minified by a couple of characters, that may build up to many of characters on large stylesheets.
Since an id like #name should be unique to the page, there is no reason per se to put the element with it. However, div#name will have a higher precedence, which may (or may not) be desired. See this fiddle where the following #name does not override the css of div#name.
I would guess that including the element name in your id selector would actually be slower – browsers typically hash elements with id attributes for quicker element look up. Adding in the element name would add an extra step that could potentially slow it down.
One reason you might want to use element name with id is if you need to create a stronger selector. For example you have a base stylesheet with:
#titlebar {
background-color: #fafafa;
}
But, on a few pages, you include another stylesheet with some styles that are unique to those pages. If you wanted to override the style in the base stylesheet, you could beef up your selector:
div#titlebar {
background-color: #ffff00;
}
This selector is more specific (has a higher specificity), so it will overwrite the base style.
Another reason you would want to use element name with id would be if different pages use a different element for the same id. Eg, using a span instead of a link when there is no appropriate link:
a#productId {
color: #0000ff;
}
span#productId {
color: #cccccc;
}
Using #name only:
Well the first obvious advantage would be that a person editing the HTML (template or whatever) wouldn't break CSS without knowing it by changing an element.
With all of the new HTML5 elements, element names have become a lot more interchangeable for the purpose of semantics alone (for example, changing a <div> to be a more semantic <header> or <section>).
Using div#name:
You said "with the reasoning that it's slightly faster". Without some hard facts from the rendering engine developers themselves, I would hesitate to even make this assumption.
First of all, the engine is likely to store a hash table of elements by ID. That would mean that creating a more specific identifier is not likely to have any speed increase.
Second, and more importantly, such implementation details are going to vary browser to browser and could change at any time, so even if you had hard data, you probably shouldn't let it factor into your development.
I use the div#name because the code is more readable in the CSS file.
I also structure my CSS like this:
ul
{
margin: 0;
padding: 0;
}
ul.Home
{
padding: 10px 0;
}
ul#Nav
{
padding: 0 10px;
}
So I'm starting generic and then becoming more specific later on.
It just makes sense to me.
Linking div name: http://jsfiddle.net/wWUU7/1/
CSS:
<style>
div[name=DIVNAME]{
color:green;
cursor:default;
font-weight:bold;
}
div[name=DIVNAME]:hover{
color:blue;
cursor:default;
font-weight:bold;
}
</style>
HTML:
<div name="DIVNAME">Hover This!</div>
List of Css selectors:
http://www.w3schools.com/cssref/css_selectors.asp
I have a website created by a designer entirely in a table format. I am embedding another table within its cell, the thing is my table has its own stylesheet. When I link mine externally, the entire site get warped. All I want is my Stylesheet to work on my table.
How do I include this stylesheet without causing a conflict or override on the entire site?
If there's no better option, then give your table an id or specific class. Then use this in all your CSS declarations, ensuring the styles within will apply to only your new table. This article explains the idea of pseudo-namespacing further, which is worth considering.
So instead of:
td { border: 1px solid black; }
You would have, e.g.:
.myClass td { border: 1px solid black; }
There are two kinds of things to take care of: 1) preventing your style sheet from affecting the table used for formatting the entire table, and 2) preventing the formatting of that table from affecting your table. Your style sheet must be modified for this.
Start from assigning a unique id to your table and then using the corresponding selector in all rules of your stylesheet (see Rob W’s answer). This suffices for 1). It mostly suffices for 2), too, but not always. You should test it and have a look at the overall style sheet. There is no quick way here.
To illustrate the problematic point, suppose that you want your table to have borders around cells. For this you could have table#foo td { border: solid; }. But if the overall style sheet has td { border: none !important; }. That’s not good practice, but such things are used; authors often use !important for no good reason. In this case, if the overall style sheet cannot be changed, you would need to use !important in your style sheet, too. In extreme cases, you might even need to use !important and write selectors so that they are more specific.
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 6 years ago.
Improve this question
One of the most challenging thing I have felt while working on (complex) web application is the organizing the CSS.Here are the different approaches we have tried on multiple projects.
1: Have a different stylesheet for every web page/module.
Obviously we were very new to web apps then, and this approach resulted in too many style sheets and too much repetition of styles. We had a tough time to achieve consistency across the application.
2: Have a common style sheets which is shared across the similar web pages.
This worked well for sometime until it became too complex. Also we found that we had too many exceptions which still resulted in tweaking common styles for particular cases, which if done incorrectly can affect different parts of the application and at some point it becomes difficult. Also having a large development team (across different time zones) and tough project timeline didn't helped our cause.
Although #2 works, but still we have seen our products still doesn't have the similar UI quality and consistency as we would like to.
Are there any CSS style guidelines that one should refer for very complex web 2.0 application. How do other people maintain their stylesheets?
I've found myself in similar situations.
First off, make sure that you're using CSS effectively. If you don't feel like you're an absolute pro at using CSS, take some time to study up and you'll significantly reduce redundancy and end up with a stylesheet that's easier to work with.
In most cases, there isn't much of a performance hit if you consolidate all of your styles into one file, and in fact, splitting your styles into dozens of files just so that you can be sure to exclude any that won't be used is likely to result in longer loading times because of all of the extra requests. But as I'm sure you know, a massive CSS file can quickly grow into a headache to maintain.
Consider this hack to achieve a compromise. Use your language of choice (PHP for me) to serve up your CSS. By that I mean include your style file like this:
<link rel="stylesheet" type="text/css" href="styles.php" />
, have the header of that file return it with the text/CSS content type, and have that file
a) Pull multiple stylesheets into one file
and/or
b) Change how the styles are written depending on various parameters (file being loaded, user data, time of day, etc.)
A is a good solution overall for reducing developmental headache and page-loading overhead. B will likely necessitate you also setting appropriate file expiration dates to avoid having the browser just ignore whatever new styles you want to generate at the moment in favor of what was downloaded on the last visit. Since you can usually accomplish the same thing in B as you can by simply having a static stylesheet and dynamically-written element class/ID names, it's generally not an ideal solution unless if you're doing something really strange.
And get a designer to advise you on this kind of stuff. Often it's hard for us developers to wrap our heads around some of the finer points of efficient CSS as well as people trained in that specific area.
I've been in this a lot of times. First, in the early times, I used to do just a stylesheet with everything inside, not much anyway, was the old times; then I decided for your second approach, the first one I luckily thought it was a mistake, too much code and pieces floating around...
The second approach is good up to the time when you start to make questions...
I mean:
Should the background style for this div go in the graphic.css or in the layout.css?
Should the font style go in fonts.css or in layout when comes to the width of the P?
Should the margin for a title with the icon position div go to the graphic.css or to the layout.css or to the fonts.css (it would be simpler to use the same declaration for the icon, the text and the position...)?
Then you realized there's something wrong about this approach.
What I do now is commenting. A LOT.
template.css -
/* ////// Headers ////// */
#header {
width: 1004px;
height: 243px; /* 263H-20MARG=243H */
padding: 20px 0px 0px 0px;
background-color: #000000;
background-image:url('../images/redset/top1-bk.png');
background-repeat:no-repeat;
background-position:right top;
clear: both;
}
/* logo */
#logo {
background-image:url('../images/redset/wh-logo.png');
background-repeat:no-repeat;
width:327px;
height: 263px;
float: left;
margin: -20px 0px 0px 0px;
}
#logo a {
width:327px;
height:263px;
}
/* Top menu & Banner */
#menuybanner {
text-align: center;
/* margin-right: 65px; optional*/
}
#bannerz {
height: 152px;
width: 653px;
text-align: left;
margin-right: 24px;
/* optional: width: 100%;
margin: 0px */
}
#bigmenu {
text-align: left;
margin: 18px 0px 14px 74px;
}
#bigmenu img {
margin: 0px 22px 0px 0px;
}
Originally this would have been in three different css: layout, graphics and texts. Now I know what everyone does.
By the way I know it rises the weight of the archive but I prefer not to do some mixed effects, cause everyone that comes after me and reads the css should be able to understand what I did and css like these:
a, .b, .c, .d, #f, #2 { background-color: black; }
Are really hard to unveil. Of course if you need to do it, go ahead, but I mean, sometimes they are just grouped like for nothing just to be more cryptic... like moodle... hahaha.
Hope being of help.
See ya.
You want to take advantage of cascading nature of CSS and the ways rules are inherited.
Code first the most general cases and then change specifics.
For a normal size project this should not get out of hand at all.
To see things more clearly you can use an index sheet and call other stylesheets from it. When you want to make changes you will know which stylesheet to go to and you will save time. Here is an example from one of my prqjects.
/*
This is the CSS index page. It contains no CSS code but calls the other sheets
*/
#import url("main/reset.css");
#import url("main/colors.css");
#import url("main/structure.css");
#import url("main/html-tags.css");
#import url("main/sign-up-sign-in.css");
#import url("main/pagination.css");
#import url("main/menu-items.css");
#import url("main/teachers-list.css");
#import url("main/footer.css");
#import url("main/misc-custom-sections.css");
#import url("main/error-messages.css");
Good luck finding your own style.
I use one mastersheet template.css which styles my main template. For any site which requires a seperate bit of styling that can't be covered by the main template I either put it in the site head, if it's short, or create a new sheet for that case.
Ideally I want to design the template.css file to be flexible to cover most cases.
I typically try to group my CSS by visual elements, and only include relevant stylesheets for a given page to keep my load times low. Using PHP or whatever environment you use to dynamically merge the required stylesheets into a single stylesheet for a given page is a good solution.
One thing that helps me is that I actually created pseudo namespaces for my CSS. I know that CSS 3 has support for namespaces, and that makes it easier, but since some browsers don't support it, this is what I do:
Create folders and files relevant to your project ( I use Java namespace style )
For example /css/com/mydomain/myprojectname/globalheader.css
Next, I use class names that map to the file system location
For example <div id='header' class='com-mydomain-myprojectname-globalheader-topClass'>
Use separators and good comments in your css file
For example /*---------------------------- begin link section --------------------*/
Use PHP or whatever to load these files and combine them into one stylesheet on load ( you could cache the resulting sheets if you are really clever. The namespace convention will prevent collisions between class names.
While the designers think this is verbose, it makes it really easy to find specific css classes in the file system, without a load time hit. Also, you won't have the problem of one designer / developer overwriting another's classes.
maintaining css files is a LOT easier if you can get everyone on board with utilizing cascading properly and keep your targeting strengths to the minimum.
Make sure that elements inherit styles and that overrides aren't too heavy will keep your css from getting crazy. By doing this, you then allow yourself to have just 2 or 3 style sheets for layout/base styles and overrides. If you put heavy control levels on what gets into the layout/base style sheets, and make regular trips in to reassess whats in the overrides sheet to see what can be moved up to the base and what can be simplified you'll free yourselves up to allow people to override at will, but also to keep control of creep.
There's my theory...
How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
There are a number of different things you can do to aid in the organisation of your CSS. For example:
Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc.
Comment your CSS code.
Why not add a table of contents?
Try using a CSS framework like 960.gs to get your started.
It's all down to personal taste really. But here are a few links that you might find useful:
http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/
http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/
http://www.louddog.com/bloggity/2008/03/css-best-practices.php
http://natbat.net/2008/Sep/28/css-systems/
Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:
Make class names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than left, use something like header_links_object2_left.
Use id rather than class only if you know there will only ever be one of an object on a page. Again, make the id unambiguous.
Consider side effects. Rules like margin and padding, float and clear, and so on can all have unexpected consequences on other elements.
If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.
And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.
Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file.
Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend Firebug enough.
The best organizational advice I've ever received came from a presentation at An Event Apart.
Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:
Reset rules (may be as simple as the
* {margin: 0; padding: 0} rule,
Eric Meyer's reset, or the YUI
reset)
Basic element styling; this
is the stuff like basic typography
for paragraphs, spacing for lists,
etc.
Universal classes; this section
for me generally contains things
like .error, .left (I'm only 80%
semantic), etc.
Universal
layout/IDs; #content, #header,
or whatever you've cut your page up
into.
Page-specific rules; if you
need to modify an existing style
just for one or a few pages, stick a
unique ID high up (body tag is
usually good) and toss your
overrides at the end of the document
I don't recommend using a CSS framework unless you need to mock something up in HTML fast. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own "framework" as you figure out what code is shared by your projects over time.
Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.
Cop-out line of the year: it depends.
How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?
My favorite place to go for information like this is CSS Zen Garden & A List Apart.
There are two worlds:
The human editor perspective: Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...
The consumer perspective: The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.
I recommend you to start with a CSS framework:
Blueprint if you like smaller things
or YAML for a big and functional one
There is also a list of CSS Frameworks...
And then bring it in shape (for the browser) with a CSS Optimizer (p.e. CSS Form.&Opti.)
You can measure the Results (unpotimized <-> optimized) with YSlow.
A few more tips for keeping organized:
Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip
Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.
Semantic HTML with good class names can help a lot with remembering what styles apply to which elements.