CSS coding style [closed] - css

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Are there any good CSS coding style/standards?

Here is a good one:
http://www.phpied.com/css-coding-conventions/
But the important thing is to pick something and stick with it for consistency.

I agree with most of the points at Andrew Hare's link, but I strongly believe
.class-name {
color: green;
}
is inferior to:
.class-name
{
color: green;
}
on the grounds that:
.class-name, .class-name2 {
color: green;
}
or:
.class-name,
.class-name2 {
color: green;
}
are considerably less obvious to grep or read than:
.class-name,
.class-name2
{
color: green;
}

There's no standard standard, as it were. There are most certainly plenty of in-house standards and conventions. And there are certainly known best practices.
I stick to the following:
Structure your CSS according to it's purpose
That may involve separating out CSS concerns into different files (layout.css, colors.css etc). This may just as well involve clearly dividing up a single CSS file into clear sections along the same lines.
Be as specific as possible
Selectors have differing weights. ID-based selectors are more specific than class-based selectors. Chained selectors (e.g. body div#container div#content p) are very specific indeed.
Start out being as specific as you can, even if it appears you're being too specific. It's quite easy, later down the line, to merge together two very specific style definitions by removing one and making the other less specific.
A style definition with loose specificity may target elements you did not intend in ways that are not immediately apparent or obvious. I think this is the most common cause of CSS frustrations ("Why on earth will this div not let me set a top margin?")
Always specify every single style you wish to apply for a given defintion
For example, if you want all your paragraphs to have pink text, set the text colour to pink and also set the margins/padding/background colour/font and so on.
Don't rely on browser defaults to be suitably consistent. Certainly for the most commonly used elements the main browsers tend to use very similar if not identical default styling.
If you set all the relevant styles yourself you know what the end result should be.
If you only set those styles that are most immediately obvious, the end result will be (most likely) a combination of the browser defaults and your styles. This will eventually catch you out at some point. I think this is the second most common cause of CSS frustrations.
Use ids for styling unique elements
It's generally a good idea to apply an id attribute to any unique element that is going to be interacted with in any way. For CSS this will let you apply suitably specific styles more easily.
Use an id on a unique page
Pages that are significantly different in style and layout to the majority (homepage, search results, 404) should have an id on the body element. This gives you the specificity you need to ensure that your careful homepage styling doesn't get affected by styles you later apply to some internal content page.

Pretty coding style VS site speed
I've been working with pretty huge CSS files, and found out some pretty interesting things that I've never read about before.
#import
One thing is using #import. That's actually a bottleneck - by going away from using #import completely, the site got a lot more snappy.
#every .style { in one line }
When the browser reads a document, it reads line by line, so by switching from my pretty coding style to this, I accomplished 2 things;
A even more snappy site
Less scrolling, better overview. Why? Cause I first scroll down to find the style I'm going to work with, then it's all in the same line and it's not hard to scroll your eyes along the line to find what you're looking for.

The main good coding style is to actually separate css files according to their goals.
See Progressive Enhancement.
That way, whatever coding convention you will choose, you will have consistent and manageable separate css files... easier to debug.

When I code in CSS:
In first part I write the class and id
In last part I write the general element (p, font, etc) because the class and id have more importance for inheritance
I write comment if I want a particular behaviour with IE or with MoSE Browser
You can see some example in CSS Zen Garden
Generally I insert the most important elements over the other: if there's
p.important{/*features of a class*/}
p {/*features of a general element */}
Reading the CSS file I know the format rules before about the most particular elements, after the rules about the most general elements.
It's an habit in programming Java.

Put your css rules (ex: "color: red;") in alphabetical order and also put your selectors (ex: "div { color: red; }") in order they appear in your markup. Separate code for structure from skin.

Just from experience I used to write quite long CSS style sheets. Now my style sheets typically are half a page.
So keep it simple(KISS), line based (greppable) and keep it compact (use font: instead of font-size etc etc.).
Also I highly recommend using CSSlint to check your code for fluff.

Check Sass out. It's a template language for CSS that makes your source code DRY:er and mucho easy to read. Even if you're not using ruby you can use it for this task and automate the building of your css files from Sass source. And there are probably Sass implementations in other languages too.

There's probably loads. At our work we use the following:
/* =div a comment about my div */
div#mydiv {
border:1px solid #000;
}
The =div allows us to search against all div elements by using the search functionality. There's loads more though, I've used many different variations of this in the past.

In addition to what others said, remember that the C stands for 'Cascading', i.e. subelements inherit from top level elements. Sound simple and straight away. But I have often seen CSS files that contain redundant declarations, e.g. for font styles. This makes a CSS more complex and hard to maintain.
So before you add something to your CSS make sure that it is not redundant, i.e. check parent elements and remove redundant declarations from children.
Given this you should organize your CSS in a way so that high level elements (like declarations for the body class) are mentioned first and more specialized elements last.

This might also be helpful, a few tips to keep your CSS styles DRY - as in "Don't Repeat Yourself" link text

I will strongly recommend looking at Less: http://lesscss.org
While not really a standard, it has been gaining a lot of momentum recently. Less is css extension that runs in the browser bringing variables and functions into the language and therefore allowing templating.

Related

Is it possible to nest SASS selector in the source without outputing them nested? [duplicate]

This question already has an answer here:
Is there a SASS rule for outputting a descendant to the root?
(1 answer)
Closed 6 years ago.
For example, I want to make my code easier to read by doing this:
#article{
...
#article_inner{
...
}
}
However, I want it to compile into this:
#article{
...
}
#article_inner{
...
}
Is this possible using SASS?
Yes, #at-root will do what you want.
However, I question the premise of your question.
First, let's assume you really want to write #article { #article-inner {. For this, SASS will generate the code #article #article-inner {. You want it to generate #article-inner {. But why? Presumably you are concerned about the possibly lower efficiency of parsing, downloading, or applying the former as compared to the latter. Actually, though, any differences in efficiency would be miniscule to non-existent.
Second, I wonder why you think nesting the rules is "easier to read". Actually, to me it's harder to read. Presumably you think following the structure of the HTML is going to make it easier to read. Actually, following the structure of the HTML makes your CSS brittle. In computer science terms, this is called "coupling", generally considered a Bad Thing; in this case, you are coupling your HTML too tightly to your CSS. For instance, if for whatever reason #article-inner moved, or appeared somewhere else, then, even though the ID matched, your rule would stop working.
Experienced SCSS coders make very light use of its nesting capabilities. Instead, they write rules that are orthogonal to the HTML, which can be combined to create a number of styling effects, without being slavisly bound to the hierarchical structure of the HTML. Good SCSS coders I know limit themselves to nesting in the case of things like .class { color: red; &:hover { color: blue; } }, or in other cases to one level at most. In your case, if you have to use #at-root to do what you want, you have now actually made your code less readable in the name of readability.
SCSS is not going to live forever. Some day CSS will handle much of what it now does for us, including variables. Some shops are already moving away from SASS, with its ugly, verbose macros, mixins, hard-to-maintain features like #extend, and excessive nesting, back to raw CSS or forward to more modern preprocessors like suitCSS. We need SASS less and less for vendor-prefixing; other preprocessors support modularized, automated vendor prefixing tools. For all these reasons, therefore, it's not unreasonable when writing SCSS today to consider the potential that your code might need to be ported away from SCSS sometime in the future. That would indicate you should avoid using lots of SCSS-specific features when they're not really necessary, such as the nesting in your case.
If you want readability, add comments, which you should be doing anyway.
#article { ... }
/* The `#article_inner` element is inside `#article`.
#article_inner { ... }
More generally, I would question an ID-based approach to writing CSS. Presumably you intend to specify a bunch of properties on #article-inner, like font size, background, padding, or whatever. I've seen CSS where there are a dozen properties or more. What is the point? You might as well just write the properties in a style attribute directly on the element; at least then, you'd only have one file (the HTML) to manage. Instead, knowledgeable CSS designers create small, utility-like classes that can be applied to many elements. For instance, they might define a PaddedGrayBox class, that handles the padding and background. Then, they write in their HTML
<div id='article-inner' class='PaddedGrayBox FloatRight...'>
Now this is more readable. Someone looking at the HTML can immediately see what kinds of styling are being applied. If you take this approach consistently, you may find that you are able to do away with using IDs altogether, although I know that would be quite a departure for jQuery-oriented programmers who believe that doing $('id') (or getElementById) on every other line is the core of JavaScript programming.

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.

What is the best way to use CSS? (NOT *learn* but really *use*) [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
I know CSS and I'm learning more and more common pattern. However, I always feel like I'm hacking instead of doing it the right way.
For instance, some people I respect tell me that using css reset is unnecessary while others live for it. Also, there are so many great css framework (for grids, etc.) that even thought I understand them, I never really know when to use them.
So, basically, my question is: Once you understand how CSS work, is there a recognized "best" approach used by excellent web developer? As in python, one should try to use the common pattern and read PEP 8. Or, in C++, after understanding the syntax, reading the effective serie by Meyer is an excellent "second" read.
Sorry for taking that long to explain.. I just didn't want to have answer like: Read "Beginning CSS" which explain how to change the background or how to set font. I'm really looking for a good standard approach.
Should we use reset?
Should we use only one file per site? One for homepage and one for the rest? One basic file and once different for every big sections?
Is it bad to have a 2k+ css files? Does it mean it should have been refactored and that it contain to much duplicate?
Should I define parent at the top for normal font, color, h1, etc., and then, when it's different change it per sections.. or instead always use the standard one and redefine each and every section.
Should I use .class and #id a little bit everywhere, or should I try to minimize them and instead use long descriptor such as:
.content .main tr td span a
or
span.classname a
Thank you!
tl/dr:
What's the best "second" read once you already understand CSS but would like to use it in a clean/professional way?
[EDIT]
Thanks all for your answer. I know I asked quite a lot of questions.. but they were only examples for the real question which is: What is the best "second" read once you already understand CSS but would like to use it in a clean/professional way. I.e., I was hoping to read a book explaining the examples I proposed.. but also would explain lots of other things that aren't css-syntax but more css-best-professional-use.
People will have a range of answers for these questions, but here are the approaches I would take:
Resetting
If you're working on a fragile layout -- one that could easily break if a few pixels aren't where you expect them to be -- consider using a reset. I would look into normalize.css. Instead of completely overwriting browser defaults, it smooths out the differences between browsers.
You could also consider resetting specific elements if you find yourself adding a lot of margin: 0; to your stylesheets.
Splitting up CSS documents
Google recommends splitting them up so that individual pages aren't forcing users to download lots and lots of stylesheet rules that aren't actually used on the page that they're visiting.
Yahoo recommends combining files to minimize the number of HTTP requestion
Obviously, finding a balance is important, and this SO question weighs some of the pros and cons.
Classes and IDs or long chains of selectors?
I try to keep classes and IDs to a minimum (in both my HTML and my CSS). They tend to be more fragile when you're building pages that others will update with WYSIWYG editors. I add a few IDs or classes to large blocks of the page, then use CSS to target specific elements within those blocks. This is easier if you avoid deep nesting in your HTML as much as possible.
Working with a CSS preprocessor such as LESS or SASS can help you write more readable stylesheets. The ability to nest style rules in both LESS and SASS has helped me avoid a lot of specificity-related issues.
Still, specificity is a good CSS topic to be familiar with:
CSS-tricks has a good article covering specificity
The W3C's own documentation is worth reading.
Additional Resources
As far as additional reading is concerned...
SitePoint's collection of articles and tutorials on CSS is a great resource for more advanced CSS tutorials, and they also feature some good articles covering CSS issues that are more advanced than what you'd find in many beginner-level books.
Resets: I think yes, some dislike them, so it's up to you to figure out which one you like
Split vs. Unified files: Depends. There are advantages to both (chorus: advantages, advantages!) One CSS file is easier to browse, and you can clearly find relationships in a single file. Then again, if you have planned the structure of your site, are developing compartmentalized widgets, or have lots of people working on the CSS committing files, a decentralized method might benefit you. With multiple CSS files, you can always use a compressor to serve them to the client as a single file, so it's more of a maintenence question.
Large Files / Line Count: Are you saying you have 2,000 CSS files (holy crap!) or 2,000 line CSS files? Both aren't great, although the latter can be managed quite easily in an IDE that provides outlines and handles inheritance for you.The former...well, at least you have job security.
Parent Definitions: Again, no right answer. The CSS rules for a small site will vary greatly from an enterprise level site. A good starting point might be checking out how jQueryUI handles styles and then forming your own opinion from there.
Correct Selectors: Steve Souders talked about optimizing CSS selectors, coming to the conclusion that's it not worth it for your average site. So ignoring CSS optimization and based on your example, I'd say the second one is waaaay easier to maintain and ultimately far more predictable. If you HTML changes even slightly, the first one will break quickly. The second won't, and is far more portable.
There are things you can do in CSS to make your life easier. I highly recommend using a grid system for layout (blueprint, 960GS, etc). I personally like using a reset since it makes pixel perfect designs easier to manage. Other than that, research what people like Eric Meyers or site likes alistapart.com or smashingmagazine.com have to say on the topic.
tl;dr - there is no right answer, but definitely some good options
I can answer your questions based on my own experience, not necessarily the best practices out there.
I reset certain tags, but not all the tags like the "CSS purists" do. Keep in mind that if you are using certain CSS libraries, like JQuery UI, Superfish menu, etc.. resetting the tags can really mess up these libraries UIs.
I usually have one general layout/configuration CSS file and every complicated page has its own CSS file. So, every page includes these 2 CSS files plus my UI library files (JQuery UI, etc). This makes it easier for me to pin point and maintain it.
2K+?? Yes, very bad in fact. If you have file that big, you should really use YSlow to see how long it takes to load that file. The longer you page takes to load, the faster you users leave your webpage, unless they are forced to use it. :D
I always like to "scope" my CSS, by prefixing with say #app. This ensures my global setting only affects my page content and layout, and they do not override the UI libraries.
Use .class and #id in whatever way it makes sense to you. If you know this tag exists only one time, then use #id. If you know it might occur more than one time in the page, then the only option is to use .class.
As with many things there aren't really rights and wrongs, it's more about prefernce and manageability.
I use CSS Reset on some elements, I prefer the blank canvas start instead of finding a load of unknown defaults.
I don't think file size is really an issue, again what is easiest to manage is really more important. Split the file if it logical to do so.
Give some thought to optimisation and try to avoid unnecessary duplication. I like to define a parent font/styles as you call it for the most commonly used style, then just define the others as required.
Personally I like to define some common classes, i'm not sure if it's optimal but it's very usable, such as:
.bold {font-weight: bold}
.clear {clear: both}
.red {color: red}
If you do this for common requirements you can then simply use code like
<p class="bold red"></p>
<h2 class="red"></h2>
<br class="clear" />
Simples!
Use tabs. Makes it easier to see. Also i rather use .classname than #id. Example of a piece of css of one of my websites:
body {
font-family: Arial,Helvetica,sans-serif;
font-size: 11px;
background-color: #99D9EA;
}
.lcategorie {
background-image: url('http://images.alphenweer.nl/i/gradient-menu-left.png');
background-repeat: no-repeat;
padding-left: 2px;
text-align: left;
color: #FFFF00;
font-weight:bold;
width:200px;
height:20px;
display:block;
cursor:pointer;
}
.rcategorie {
background-image: url('http://images.alphenweer.nl/i/gradient-menu-right.png');
background-repeat: no-repeat;
padding-right: 2px;
text-align: right;
font-weight:bold;
color: #FFFF00;
width:200px;
height:20px;
display:block;
cursor:pointer
}
In addition to the good answers above, what you just described in your question is also otherwise called as Learning Curve.
We all go through it. It is inevitable, according to me.
The best approach probably is to make the best use of the vast resources available and then filter them out. Which is a knack developed only over time.
I don't think there are shortcuts. Although, I do agree, it would be nice to have a guiding hand to help us avoid pitfalls and time-wasters and tell us about all the best-practices.
But even those are available out there thanks to some really passionate, expert-in-their-field bloggers.
So explore-away is what I'd suggest.
If your lucky enough to have a Mac or a Hackintosh... then I highly recommend CSSEDIT (unfortunately only available on Macs). It will allow you to rapidly develop your understanding of CSS. I realize this doesn't answer your question, but if you try it, you'll understand why it is so important to the learning curve. Sadly, nothing else on windows comes close. I use windows 99% of the time and switch to my mac for CSSEDIT.

Is there an advantage to using very specific selectors in CSS?

I understand that in jQuery, it's advantageous to be more specific when using selectors so that jQuery doesn't have to traverse the entire DOM to find what you're looking for. For example, $('span.description') is better than just $('.description') if I know that the description class is only ever applied to <span> elements.
Is this the case with CSS, too? Is there any specific advantage for me to use span.description { } instead of .description { }? I'm thinking in terms of speed, optimization, etc. Am I saving the browser any work by telling it exactly where to look?
This is true in CSS -
A good rule is to descend from the nearest ID.
IDs are indexed so locating them is extremely fast. There is no reason to use more than one in your selector.
Google Code- Optimize browser rendering
This answered a lot of questions I had on the subject including this one-
I hope you find it useful.
Read up on css specificity - which is the most important reason to be more or less specific with your css.
http://www.w3.org/TR/CSS2/cascade.html#specificity
As browser performance is pretty much a non-issue (except for in jquery, as you've mentioned), my guideline is to be specific when you are controlling precedence, or when you want to make something a bit more readable in your css. Over specifying can make it tricky to re-use css selectors and make things overly complicated.
Edit
This looks like a bit of a duplicate:
CSS Performance Question
it always depends on your amount of html code and the structure. It is definitely a good idea to use especially ids and appropriate selectors. (ie #nav li instead of li.nav). Since browser first load the html and then apply the css you are helping a lot.
This said, when it comes to pure css (no jquery) the difference in speed is nowadays not easy to distinguish, because the rendering engines are highly optimized - especially when it comes to applying css. So normally it shouldn't matter.
As far as I know, how specific your selectors are make very little difference on the performance.
The two areas where more specific selectors are most useful, is to reduce the risk that it's not applied where you don't want it, and to make one selector take precedence over another.
A more specific rule has precedence over a less specific rule, so:
span.myclass {}
has precedence over:
.myclass {}
(no matter what the order is in which the rules were declared)

CSS Selector Style

I didn't see anything on here about it with a quick search, if there is let me know.
Here is an example of a CSS selector I'd write.
div#container div#h h1 { /* styles */ }
div#container div#h ul#navi { /* styles */ }
div#container div#h ul#navi li.selected { /* styles */ }
I write all my CSS like. This allows me to stop from having styles floating around and I can technically re-use the same class name easily. For instance, I might use .selected on multiple elements across the site.
I also specify the element type (div, ul, etc) before the class/id unless the style is used for multiple elements. I also specify the element before id's even though there will only ever be one id because it allows me to know the element easily when reading my CSS. For instance I'll know right off the bat that em#example will most likely have a font-style of italic.
This isn't a question about CSS formating, it's about writing selectors.
I'd love to hear opinions on this approach, as I've used it for years and I'm reevaluating my stying.
Although it's somewhat off topic I also write my selectors like this for selector libraries (like jQuery for instance). Although I haven't looked into jQuery's internals to see if there is performance issue with specifying the element with an ID.
I think it really depends on what the selector is for.
Almost every site has one or a few style sheets that "skin" the site - fonts, text colour, link colour/hover, line spacing, and so on, and you don't want these selectors to be very specific. Similarly, if you have a component or element that's reused in many pages and always needs to look the same - like let's say the tags right here on SO - then it's going to be a pain to maintain if you use selectors based on the ID.
I would always use the ID in the selector if it refers to a specific element on a specific page. Nothing's more frustrating than trying to figure out why your rules don't seem to be working because of a conflict with some other rule, which can happen a lot if everything is classes. On the other hand, I think that nesting the IDs as you are (#container #h) is redundant, because the purpose of an ID is to be unique. If you have more than one element with the same ID on the same page then you can end up with all sorts of problems.
It does make the CSS slightly easier to understand when your selectors provide some idea of the "structure" that's being represented, but, to be honest, I think that goes against the idea of separation of concerns. The #navi might be moved outside the #h for perfectly legitimate reasons, and now somebody has to update the style sheet for #navi, even though nothing about it has changed.
A bit subjective as Darrell pointed out but that's my two cents.
While the question is a little subjective I have to say I agree with your thinking. I think defining the element before the selector is clearer when reading the code and it is less error prone.

Resources