is using class names like 'right' considered bad practice? - css

If I have class names such as "left", "right", "clear" and xhtml like
Continue
With CSS like
.right {
float: right;
}
I know it's not a semantic name, but it does make things much easier sometimes.
Anyway, what are your thoughts?

I don't think that's a very good idea. Now when you (or a future maintainer) go to change your website layout, you'll either have to change .right to {float:left;} (obviously a bad idea) or go through all your HTML files and change right to left.
Why do you want that particular link to be floated right, and the other .continueLink's not to? Use the answer to that question to choose a more descriptive class name for that link.

css is about presentation of the structure of your html page.
Meaning its classes should represent the structure of the document ('article', 'extra-links', 'glossary', 'introduction', 'conclusion', ...).
You should avoid any class linked to a physical representation ('left', 'right', 'footnotes', 'sidenotes', ...), because, as the Zen Garden so clearly illustrates, you can decide to place any div in very different and various ways.

The purists will say don't do it, and the pragmatists will say it's fine. But would the purists define .right as float: left?

It might be advisable to avoid names that are the same as values in the CSS specs to avoid confusion. Especially in situations where multiple developers work on the same application.
Other than that I see no problem. I would qualify the right or left name like this: menuleft, menuright etc.

Being a purist, I say no don't do it. For reasons mentioned earlier.
Being a pragmatist, I just wanted to say that never have I seen website rework that involved pure html changes without css, or pure css without html, simply because both parts are being developed with the other in mind. So, in reality, if somebody else would EVER need to change the page, I bet my salary they will change both html and css.
The above is something that collegue purists around often tend to ignore, even though it's reality. But bottom line; no, avoid using a className such as "right". :-)

.right and other classes like that, certainly makes it quick to write create a tag with a float:right rule attached to it, but I think this method has more disadvantages than advantages:
Often a class-style with a single float:right; in it will lack something, your example wil only float right if the other class rule contains a display:block in it, since an "a" tag is not a block level element. Also floating elements more often than not needs to have width an height attached. This means that the code in your example needs additional code to do what it says, and you have to search in two places when you have to change your css.
I tend to style my html by dividing the page into different div-tags with unique id's, and then styling elements in these div by inheritance like this.
div#sidebar { float:right; width:200px; }
div#sidebar ul { list-style-type:none; }
This makes it possible to partition my css files, so that it is easy to find the css-code that styles a particular tag, but if you introduce .right and other classes you are starting to disperse the rules into different areas of the css file, making the site more difficult to maintain.
I think the idea of having a very generic classes is born from the wish of making it possible to change the entire layout of the site by changing a couple of rules in a stylesheet, but I must say that in my 8 years of website development with 30+, different sites under my belt i haven't once changed the layout of a website and reused the HTML.
What I have done countless times is making small adjustments to regions of pages, either due to small changes in the design or to the introduction of new browsers. So I'm all for keeping my css divided into neat chunks that makes it easy to find the rules I am looking for, and not putting the code in different places to achieve a shorter stylesheet.
Regards
Jesper Hauge

Yeah, semantically speaking it is wrong, but, for example, there are times when I'm positioning images within a block of body copy and I'll give them the class "right".
Maybe "alt" is a more suitable class name.

Related

Using nth-child or creating new classes in CSS?

I've just started my first project which is building an admin panel. My task is to create HTML and CSS - sort of a base of design to process further to the back-end developers.
I was asked to keep CSS simple and classes as descriptive as possible ( could be long ) and to use Bootstrap.
To avoid creating unnecessary classes which could be used once or twice I decided to go with :nth-child since I thought giving new class to each column is too much. Additionally I created few base classes that might be used for adding 0px padding and margin.
Unfortunately, as I was writing more and more code I've noticed that some CSS code looks like this:
.print-history-advanced-search > [class*='col-']:nth-child(5) > .form-group > .form-horizontal > .form-group > [class*='col-']:first-child
And it is not a single line.
Additionally, I've noticed that sometimes that when I am making a new class and it has lots of parent elements, I cannot write the CSS selector by its own, but I need to state the parents of the this particular element and put the class at the end, which does not make sense.
Is there any solution I could use to avoid creating classes that are simply used in one or two divs, but also make the CSS code less chaotic and avoid very long names? Or maybe I should just give up on children and nesting and work with just classes?
Thank you for your help!
Have a nice day!
If you want to write good CSS, then I'd suggest the BEM model is a good route to go down.
The essentials are;
No element/selector heirachy
No use of elements in selectors
Class based styles only
BEM stands for Block, Element, Modifier - which is how your class names are formed. Borrowing an example from their site;
.form { }
.form--theme-xmas { }
.form--simple { }
.form__input { }
.form__submit { }
.form__submit--disabled { }
<form class="form form--theme-xmas form--simple">
<input class="form__input" type="text" />
<input
class="form__submit form__submit--disabled"
type="submit" />
</form>
You can see there's a form Block, and then a form__input and form__submit Element, and then a form__submit--disabled Modifier.
Depending on your needs I would recommend using css preprocessors like SASS,LESS.
You’ll find that as a website grows, you’ll develop a pretty long, scrolling list of various elements and CSS rules. Some of the rules might overlap or override each other eventually (in that case, usually the more specific rule will win).
You can end up with a lot more code than you expected, especially considering the different variations of a rule you need for different browsers and screen sizes.
There are many ways to refactor your CSS code to make it easier to navigate and use. Some of the easiest methods are the most effective and have the most mileage. Here are some of the quickest ones:
Keep your spacing uniform: Maintain the same spacing between rules
and within declarations throughout your file so that it’s easier to
read.
Use semantic or “familiar” class/id names: Instead of using a class
name like “bottom_menu”, try using the semantic tag “footer”. Or
when you have an image in your “contact” section, make sure you’re
using a class on your image like “contact_image”
Keep it DRY (Don’t Repeat Yourself): Ideally you want to repeat as
little of your code as possible. Do you find the declaration
“background-color: #000″ repeated throughout your CSS file? Consider
typing it once and instead, using multiple selectors on the one
declaration.
Put your tidiness to the test with these tools: Run your CSS through
CSS Lint or W3C—these will help to parse your CSS file correctly,
and highlight problem areas. Your web browser’s developer tools are
also extremely useful for pinpointing specific elements on your
website and using the area as a sandbox to experiment with different
styles and positioning.
Have a look here for more info

How to share common CSS styles

On my page I have few blocks (div) that have the same style regarding background and border (menu panel, info panel, footer panel, ...).
Now I would like to write that style only once and not repeat it for every panel. Yet I don't see any comfortable way of doing that.
One approach I investigated was to introduce a dedicated class (for example panelClass) that would capture the common panel styles. Then in (X)HTML I would just add that class to every element that is supposed to be a panel.
But this doesn't feel right. After all I would be "revealing implementation" in the (X)HTML. I'm no longer able to transparently change things easily because that requires modification of the (X)HTML.
Not to mention that it introduces issues with order of the classes (and thus order in which CSS attributes will be overwritten if needed).
EDIT: (an extended explanation for kolin's answer)
By “revealing implementation” I meant that the (X)HTML (“the content”) is much more strongly connected to the CSS (“the presentation”) than I would like them to be. Maybe I’m pursuing an unreachable ideal (maybe even an unreal or a dummy one!) but I’m trying to keep “the content” separate from “the presentation”.
Thus having a class menu isn’t bad because it describes “contents” not “presentation”. While using instead (what I understood from the cited articles and few others on that site) classes like menu box bordered left_column is bad because it mixes presentation with contents. Once you start adding such classes you might very well add that CSS directly to style attribute. It sure would be much more work and an unmaintainable result but conceptually (when regarding contents-presentation separation) it wouldn’t make a difference.
Now I do realize that in real life for real pages (rich and nice) it is virtually impossible to keep contents entirely separate from presentation. But still you may (should?) at least try to.
Also just look at the “But” in the end of the article The single responsibility principle applied to CSS. In my opinion the island class he used is already presentational because it does not describe contents. It describes how to show it. And that is immediately obvious once you see how widely he used (or might have used) that class on elements having nothing in common as regarding contents.
END EDIT
Another approach was to use selectors grouping. So I would have something like:
#menu, #info, #footer {
background: /* ... */
border: /* ... */
}
This avoids the need to modify (X)HTML. But still causes order issues. And also makes it hard to group styles logically. Especially if they are distributed among many files.
I think that what I really would like to have is to be able to name a group of attributes and just import them somehow in selectors. Something like #include in C++ for example. Is there any way to achieve this? I doubt it but maybe...
If not then is there any other method?
Using classes to define styles is the correct way to do it.
One approach I investigated was to introduce a dedicated class (for example panelClass) that would capture the common panel styles. Then in (X)HTML I would just add that class to every element that is supposed to be a panel.
For me this is exactly the way I would do it.
But this doesn't feel right. After all I would be "revealing implementation" in the (X)HTML.
is there a security problem with revealing implementation?
A few selected posts from Harry Roberts :
http://csswizardry.com/2012/04/my-html-css-coding-style/
http://csswizardry.com/2012/04/the-single-responsibility-principle-applied-to-css/
http://csswizardry.com/2012/05/keep-your-css-selectors-short
I find his style of using CSS eye opening, and it may help you
update
Following on from your update, I agree with you that you should try and seperate structure from presentation, although there will be times where we can't quite manage it. Whether it is fully possible or not, i don't know.
I partially disagree about the island class, the padding property to me kind of hovers over the border of structural and presentational. structural because it alters the layout of whatever element it is applied to, presentational because the padding alters how it looks on the page.
in an ideal world you should never need a class attribute that encompasses menu box bordered left_column, because you would write a couple of classes that seperate out the structure and presentation.
thinking about your case I might create a panel class
.panel{
margin:10px 0;
padding: 10px;
display:block
}
and a panel-display class
.panel-display{
background-color:#1111e4
}
.panel-display > a{
color:#fff
}
in this way I could just play with the presentation without affecting the structure of the site.
(n.b. I'm not sure if this helps you in anyway!, it just seems logical to me)

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.

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.

CSS coding style [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 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.

Resources