CSS coding conventions

September 30th, 2005. Tagged: CSS

Motivation

Why standards and conventions? Well, it makes the code more predictable. You know where to look when you need to change/debug something and also other coders can pick up easier if they know what conventions you followed. PHP (actually PEAR) has it, Java has it, but I couldn't find anything for CSS, so here are a few ideas.

The important thing to remember is - it's not that important what exactly is a chosen standard or convention, the most important is that there is one. The rest, the details, is just common sense, and since "the common sense is not common to everybody", pick whatever makes sense for you. Below is a suggestion to get you started and build upon.

By example

OK, here's everything this post is about, in a few lines, the rest is just elaborating on this:

.container-subcontainer-general-specific {
    font-family: Verdana, Arial, Helvetica, sans-serif;
    font-size: 1em;
}

Terminology

Before starting to talk about the coding style and conventions, let's quickly review what are the different terms used to describe the elements of the CSS puzzle.

selector {
    property: value;
}

The whole thing above is called "a style" or "a style definition". "Style name" may be used as a synonymous for "selector".
"Property-value pair" needs a better name.

Spacing

Generally spacing promotes readability, so let's take advantage of it.

Empty lines between style definitions

Allow the separate style definitions to breathe, by adding one (and only one) empty line between them, like:

.some-class {
    color: red;
}

.another-class {
   color: blue;

}

1 tab = 4 spaces

Indentation also helps with the readability of the code. So put every property-value pair on a new line and indent it with 4 spaces from the beginning of the line. You can use a tab for indentation, it doesn't matter, this is just a personal preference. To avoid hitting [space] 4 times, configure your editor to do it for you when you hit [tab]. Every half-decent text editor has this configurable (Notepad is not the best choice for a coding editor)

Space after colons

Visually emphasis on the separation between a property and value, by adding a space after the colon, like:

.class {
    prop: value;
}

... and not

.class {
    prop:value;
}

... or

.class {
    prop:      value;
}

Curly brackets

Curly brackets that embrace all property-value pairs in a style definition follow your favourite if-then-else style you'd use in other programming languages. The opening bracket may be on the same line as the selector identifier or it can go alone on the next line

.class-name {
    color: green;
}

or

.class-name
{
    color: green;
}

I personally prefer the first.

Shorthands

The use of shorthands is forbidden, because they are harder to read.I would advise against the use of shorthands, because (for a non-expert) they are harder to read. Again, like I said in the beginning, it's you who decide on the type of style to follow, so if the majority of your team is comfortable with shorthands, by all means, use them. But I think that in most cases, the use of shorthands would cause more troubles (will obfuscate the stylesheets) that outweighs their benefits (less bandwidth).
Consider:

.text {
    font: 1em/1.1em bold italic small-caps Verdana, Arial, Helvetica, sans-serif;
}

and

.text {
    font-size: 10em;
    line-height: 1.1em;
    font-weight: bold;
    font-style: italic;
    font-variant: small-caps;
    font-family: Verdana, Arial, Helvetica, sans-serif;
}

The border style is an exception from that rule, because short handing it is so widespread and because (unlike "font" and others) the order of its properties is not important. For example:

.some-div {
    border: 1px #ff0000 solid;
}

...is the same as...

.some-div {
    border: solid 1px #ff0000;

}

and is just as readable.

End of line

Good practice is to always end the lines (the property-value pairs) with semi-colon, even when not necessary (last pair in a selector). This way it's easier to add more properties later on, without even bothering to check if the previous property-value pair was properly terminated.

Naming selectors

  • The most important thing to have in mind is the content nature of the HTML document, not its presentation. Selector names should describe the content.
  • Avoid presentation-specific words in the name, like "blue", "text-gray", or "light-box". What happens when you decide to change the color? The class "blue" is actually red?
  • Cascade the name, using a dash (-) as a separator. When cascading, have in mind what the content is. What do I mean by cascading? For example: "header" and "header-logo" (you have a page header that contains a logo at, say, the top-left corner) or "footer" and "footer-copyright"
  • Use full descriptive words. Abbreviating a word may save you a few milliseconds to type initially, but may make your code harder to read, costing you more time down the road. Why crypting "product" to "prod" or the so common "txt" (just spell it out as it is, "text")? Being consistent in this will save you the time spent thinking (or trial-error-ing) how exactly you abbreviated a word five days ago. (OK, OK, there are exceptions, you can use "url" instead of "uniform-resource-locator" :D )
  • Names are lowercase. There are browser problems with case sensitivity, so you're safe always lowercasing.
  • Distinct words in the class name are separated by a dash. It's clear, readable and gives the underscore a well-deserved break. Use footer-copyright, not footer copyright, footerCopyright, FooterCopyRight, fOOtercopyRighT (god forbid!) or footer_copyright. Well, if you're attached (married ;) ) to the underscore, I guess it's OK to keep using it, but consider leaving it for your Javascript code. The dash is not allowed in other languages' variable names, so use it when you can (in CSS), plus it's somewhat consistent with the property names (think font-size, background-color, etc.)
  • Once again - use names that describe the content ("footer", "navigation", etc), rather than the presentation ("blue", "left", "big"...)

Font sizes

When possible, use em instead of pix for sizing fonts, line heights, etc. This allows your visitors to use the built-in browser text sizing, without you coding a special text size feature (which will probably limit the user to the choices you decide anyway).

Offtopic

Preferably use HTML tags to describe the content.

<h1 class="content-heading">I'm a heading</h1>

is better (semantically, for SEO, for the human reader) than

<span class="content-heading">I'm a heading</span>

Comments

We all love to read other people's code comments. Writing our own comments is probably not as fun, but is highly encouraged in the name of maintainability. When you comment, use the /* comment here */ style. Line comments (the ones with // at the beginning) are not part of the CSS2 standard and may cause issues in some browser (or alternatively used as a workaround hack for some browsers, but this is another story)

Conclusion

I can only hope this has inspired you to adopt a CSS coding style convention/standard in your daily work. I'd love to hear you opinion on this topic. Are you currently using a standard? Do you know of any available on the web?

Tell your friends about this post: Facebook, Twitter, Google+

55 Responses

  1. I agree with everything you mentioned except for the part about shorthands. If your css file is quite large, using shorthands can reduce the filesize and improve performance. Other than that, I already do the things you suggest.

  2. Your idea is good in principle, but I don’t fully agree with some of you decisions or reasoning. It sounds a bit like a case of ‘I want the world to do things the way I like them to be done’. The obvious example being your ‘shorthands is forbidden, because they are harder to read’.

    The short hand notations are some of the most valuable properties in CSS. Forbidding them just becasue you haven’t mastered them (yet) is a tad extreme. Did you know that use of the background property is encouraged over other background properties because it is more widely supported, and doesn’t take so long to type ;)

    I think, as nice as conventions are, CSS should be written to fit the situation. With larger files, my team prefers each style rule to be written on a single line so that they can easily scan down the document and find the selector they need, or easily see how the selectors are grouped. It aids maintenance. Declarations (property-value pairs) are listed aphabetically to avoid the possibility of repetition. (See http://media.monster.com/mm/eu-apac/style/thematic.css). However, I’d be the first to admit that this method doesn’t work well when you need to print a hard copy of the file.

    I think, as long as your CSS is well commented, consitently organised, and the convention works for the people who have to maintain the file – which most CSS files seem to be – the need for a convention is minimal.

  3. The terminology you were looking for at the beginning of your article…

    A style rule is comprised of a selector & declaration block
    A declaration block is comprised of one or more declarations
    A decalrtion is a property – value pair.

  4. The use of shorthands is forbidden because it is harder to read?

    WHAT A JOKE! Go back to sleep.

  5. I agree that improving readability should be considered more important than saving a couple of bytes. The amount of bytes saved by using shorthands is often less than just one image on your website. Furthermore CSS is cached and re-used all the time which diminuishes this ‘advantage’ even more. If you’re a die-hard standards nerd, sure it’s nice. If you have to work in a team on a project Stoyan’s guidelines can help efficiency in the team.

    It’s like using ternary operators extensively in PHP or other programming languages. Sure it’s a bit shorter but it’s a lot harder to understand someone else’s code if it’s full of those. Why make life harder than it needs to be just in order to save a couple of lousy bytes? Hell, you could take out ALL spacing and formatting as well and make it even more efficient. Would you do it? I wouldn’t!

    So, David, the ‘it saves bandwith’ argument is more of a joke than Stoyan’s advice to not use shorthands in my humble opinion.

  6. Thjere are a few things on which I agree, like a clear code, brackets, spaces and stuff.
    “The use of shorthands is forbidden” – are you reinventing the wheel? Shorthands are standard so why not use them? Whoever wants to read my css code better read how to use shorthands at least. I see no point in writing 5 lines instead of one. One of the purpouses of CSS is to eliminate as much as possible redundant properties. Also, i understand that’s how you see that things should be of how it would be easier to you, but “forbidden”? Says who?

  7. Thank you guys for your comments!

    I changed the shorthands part, so that it’s not as strong as it used to be. It really is up to every team to decide what style to adopt, the presence of the defined style is more important than the style itself.

    @Steven – Thanks for your input, one thing that would also be nice to have as a conversion would be the ordering of styles. Alphabetical order like you guys do is an option. Another option would be ids (#s) first, or rather the order the page is conceived and composed, I mean headers, footers, navigation, content would be the first styles to define. They would probably have to do with the positioning. Then the different other text details that have to do with the content items, not so much with the overall positioning.

    @Marco – Thanks for your backup. The analogy with the ternary operators is exactly what I had in mind when thinking about the shorthands. Yes, the language allows, but should you use them?
    echo (1 == 2) ? 3 : (4 == 5) ? 6 : 7; // echos what?
    BTW, just checked out your personal site yesterday – it’s very impressive, well done! I wished mine was halfway good as yours ;)

    @Emma – forbidden was too strong a word, I admit. This whole posting was nothing but a suggestion.

    @David – I will, thanks. Eventually ;) “One o’ these days I’m gonna…”

    Again, thank you all for your input (and for reading to begin with), it’s very much appreciated!

  8. ( Referrer from StyleGala and new in these parts )
    The tid-bit about shorthands just sounded a little too harsh. Your thoughts in general suggest perfection and adoption to one’s own style. It seems unrealistic that a group of developers would all adopt the same css style. I work for a large corp (Y!) and none of the developers have yet to adapt to a single style. Since CSS isn’t a very complicated language, it’s clearly understood what everyone is doing. Since CSS is perhaps a common API for styling documents, there’s rarely a need for exact details of how to space syntax. Granted in more complicated languages like C++ or PHP, sure, I can see how a common indenting methods and spacing can help understand the logic visually.

    On shorthands, they’re not that difficult as long as developers know what they’re doing. If you want to separate your font-family from size, line-height, weight, and style just to please those who are visually going to be peaking at your code, then have at it. If someone runs upon a shorthand property and says to themself “Oh my gosh, what the hell is going on? I can’t work with this!” – they personally need to brush up on their css.

    I hope you don’t mind that I’m chosing another side of the argument, but you couldn’t expect everyone to think this is idealistic ;)

    You do have a point on the flip side that coding conventions are in fact important, but css seems too basic of a language to consider such syntax and spacing accuracy.

  9. I agree with Dustin. While I myself have my own particular style of doing CSS: alphabetized, seperate lines for #idname and the first curley bracket, short-hand for everything, etc. – I don’t try to enforce this on other people, and can get along fine reading someone else’s CSS. I am also fine coding within the bounds of someone else’s convention.

    I think the hardest part is not reading the actual CSS, but following someone’s naming convention, such as #nav vs. #menu. I second what Dustin said – if someone can’t read CSS short-hand, then they might be in the wrong line of work. ;)

  10. If a programmer can’t read a ternary operator he’s also in the wrong line of work. Same thing really. Sure one SHOULD be able to read them, again, just like any programmer should be able to read ternary operators. However this doesn’t mean that it’s a necessity.

    It simply doesn’t serve any purpose except looking like you’re ‘really good at css’. The bytes argument is really a non-argument.

    Then there’s influential designers such as Shaun Inman even promoting to generate CSS server-side with PHP. Bye bye valuable bytes! Don’t get me wrong, I’m not really against that but this is a hot-shot designer coming up with an idea that causes CSS never to be cached anymore and no one’s complaining about those poor bytes it will cost. I bet most of those who say ‘halleluja’ on that concept love shorthand CSS selectors. Perspective, perspective. Optimizing one image on your site saves more bytes than this whole shorthand deal. Even though a CSS designer should be able to read shorthands it doesn’t mean we have to force him to eh?

    Stoyan> Thanks for you kind words about my site. I feel sort of the same about your site content-wise. It’s great stuff!

  11. Stoyan, I totally agree with you on the idea of creating a standard. In fact, I’ve been working on a Developer Markup Guide for my companies developers. With as many custom development jobs as we pump out, it gets really hectic trying to keep up with what everyone has done in the past, including myself.

    Because I am the primary, and lead, CSS developer, I decided that the standards in naming, styling, etc., should be followed by our developers in order to save time, and ultimately money. If I can go back into a 3 year old document, and find the exact class or id I’m looking for in a few seconds, the time it took to develop a standard is worth it.

    I agree about the whole short-hand thing. I try and use it as much as possible. I don’t really expect anyone who isn’t able to read CSS like a book to be editing my files anyway. :D

    On another note, I admire your level-headed replies to some of the rather rude responses to your generosity in sharing this article.

  12. Thank you guys very much for your comments! So I guess it’s safe to conclude that coding style conversions are a good thing. Pretty much everybody that commented is following some style, be it documented or not (and be it using shorthands or not ;) ).

    The thing that I think makes sense is to establish the same style for the team when working on a project, especially a project that has a good chance of being actively developed over time. By all means that doesn’t mean to take your (or my) own style and make the others code according to it. There must be a reasonable compromise with the all of the team members. This can be tricky sometimes, because everybody likes their own style and may feel uncomfortable to be pressed to use other style. But in the name of the team and the project and the common goal… And of course the better experts your team members are, the less chances of mine vs yours conflicts of style, because brighter people tend to have a bit less attitude. (Ask Paul Graham)

    Again, thanks for the feedback, everyone!

  13. Interesting article, Stoyan! I think CSS is definitely in need of some standards. Here’s one issue that’s currenly causing insomnia. Which of the following options would you prefer? Also, what’s your take on ordering these definitions and spanning them across multiple CSS files?
    __________

    OPTION 1
    Pros: Clean CSS
    Cons: Cluttered markup (i.e. class=”left small white”)

    .small {
    font-size: 11px;
    }
    __________

    OPTION 2
    Pros: Reduces redundant code
    Cons: Causes more headaches since most definition will overlap one way or another and thus require similar definitions

    div#sidebar-left,
    div#sidebar-left input,
    div#sidebar-left select,
    ul#breadcrumbs,
    div#sidebar-right,
    etc. { // taking the actual definition out of its context…
    font-size: 11px;
    }
    __________

    OPTION 3
    Pros: Keeps element definitions neatly separated
    Cons: Non-optimal

    div#sidebar-left {
    font-size: 11px;
    // more definitions…
    }

    ul#breadcrumbs li {
    font-size: 11px;
    // more fefinitons…
    }

  14. I think option 3 is the closest to what I usually use.

    Option 2 is an interesting approach, so you mean if you want to increase the font size of the breadcrumbs (ul#breadcrumbs), you’ll remove ul#breadcrumbs from this definition and move it another one that has font-size: 12px? This won’t be very friendly when you’re in the dev phase, trying out different styles and admiring the results, but still interesting.

    Like you said, option 1 will result in cluttered HTML so it’s not advised.

    You’re probably aware of this idea of separating content (HTML) from presentation (CSS) and from behavior (JS). That’s the way to go I think. So you start with the content, your HTML should be very basic, forwards-compatible-cell-phones-lynx basic so that the site works in the simplest user agents. Then you attach a stylesheet and start beautifying, for the supporting browsers, then you attach an external JS (ideally there’s no behaviour in your HTML document, only in the attached .js) and do some user experience improvements.

    In the attached CSS file, I believe you try to use as less class names as possible, ideally using only the nested, well-defined structure of your document to “navigate” to the element you want to style. Only when you cannot use nested elements to locate the one you need, or if the “path” is ambiguous, then you add a class name to that element. And when you have to use class names, use words that describe the content (not white, small, big, red, etc), this once again reinforces you to think more about the content and its structure and less about presentation.

    HTH :D

  15. Option 3 works best for me too :)

    From your last two paragraphs, I take it you build sites from a functional point of view. I, being a designer, usually start with a Photoshop design and need to figure out how to slice it while maintaining semantics and keeping the amount of classes down to a minimum. This current site I’m working on is really killing me. Please check out the CSS of this work in progress to see what I’m talking about: http://www.oscaralexander.com/cuppatalk.net/

    This is a rebuild of an earlier sliced version that I wasn’t completely happy with (http://www.oscaralexander.com/cuppatalk). Also, should you be interested in viewing the site when it’s done, drop your address at http://www.cuppatalk.net. Sorry Stoyan, didn’t mean to spam :)

    Anyway… I’m only halfway though the homepage and my CSS file counts 402 lines already. I guess that’s what you get if you want your stuff to look smooth, right? All I can think of now is: how/where do I optimize it, and how do I order the definitions to prevent it from becoming ChaoSS? ;)

  16. Hey Alex, that’s one slick site! Good job!

    You raise a good point here about you being the designer who wants to “translate” the photoshop layout to standards-compliant xhtml/css. I think the xhtml/css area is a bit of a no one’s land. What I mean is, there’s no doubt that it’s a designer’s job to do the photoshop layout. The programmer’s job is to design some OOP architecture, to query some DB tables and at the end, to fill-in-the-blanks in an HTML template. Where did this HTML+CSS file came from? Well, that depends. Depends on the team, on the project, resources, etc. It’s like you need a middle man to be the bridge between those two guys. Most of the projects cannot afford to hire Eric Mayer as the middleman so they end up employing the designer or the programmer to do the HTML+CSS thing. Seems to me like in the past, it was the designer who’d slice a picture in MM Fireworks or something and create a bunch of tables. But that was Web1.0 ;) Anyway, I got a little carried away. (And I don’t blame you of you skipped the paragraph…)

    BTW, be sure to download and listen to Eric Mayer’s presentation (podcast) on Web05 about how he approached the aListApart project, given the photoshop layouts. Here are the links to the page and the mp3.

    Back to your design. It’s very impressive and there are no tables! (I figure you knew that :) ) So I guess you have to pay the price by having more complex CSS files.

    I think you did the right thing in splitting default.css from homepage.css. It’s not a good idea to use too many CSS files though because every one makes a separate HTTP request and you increase the probability of a single file not being downloaded due to network problems between the user and the server. Anyway, on another note, it’s a usability/human attention issue that the homepage must be fast. So the more load you can take away of it, the better. Basically a common sense approach would be to have a default.css that has definitions that almost every section of the site uses, and then another css per section. There is a related trick – to have an id in your body tag and to have this id different for every section of the site. Using this approach you have the flexibility to always overwrite a class per page by using the ID. Example <body id="homepage">, <body id="registration">, etc.

    I have some other remarks for the stylesheets.
    -> You don’t need div#double-box as a selector. #double-box would be enough. Same goes for p#intro and so on. Because then in the html you have <p id=”intro” />, so just #intro is enough. Same for ul#…s

    -> you have some classnames you don’t need. Example:

    <ul id="tabs">
    <li class="active"><a href="#">Home</a></li>
    <li><a href="#">Tables</a></li>
    <li><a href="#">People</a></li>
    <li class="teaser">With <strong>5,000</strong> tables and <strong>50,000</strong> people, you'd be crazy not to <a href="#"><strong>join us</strong></a>!</li>
    </ul>

    Because you have ID “tabs” that means it’s unique for the page and from there you can access all elements. Benefiting from the tree structure of the html, I would rewrite the above as:

    <ul id="tabs">
    <li class="active tab"><a href="#">Home</a></li>
    <li class="tab"><a href="#">Tables</a></li>
    <li class="tab"><a href="#">People</a></li>
    <li class="right">With <strong class="yellow">5,000</strong> tables and <strong class="yellow">50,000</strong> people, you'd be crazy not to <a href="#"><strong>join us</strong></a>!</li>
    </ul>

    Your .tab became #tabs li
    .yellow is #tabs li strong
    . right is .teaser (more related to the content not to the presentation)
    and clearly, the “join us” is accessible through #tabs li a

    -> the last remark is the use of presentation related names, like yellow, right, etc. Think about that day when the client will come and say “I want more designs, so my users can switch on the fly”. Now yellow may become blue or something.

    Wow, it’s a long posting, I hope it helped. Anyway, you’ve designed a very nice site, so you have to deal with CSS complexity. (ChaoSS is a funny way of putting it ;) ) The pay-off is that for maintenance, CSS complexity is more manageable compared to the indefinitely nested tables.

  17. Hi again! I just Googled for ‘cuppatalk’ and noticed you had responded to my comment from way back. Thanks for taking the time, it’s definitely an interesting subject to touch upon. Now that web 2.0 is here, I feel the (old) Cuppatalk design is completely over-the-top and sooo web 1.0, that I’ll probably redesign it again to give some 37signals/flickr juice ;)

    Since I’m my own designer and programmer the gray area of HTML/CSS is not really a problem to me. I have the advantage of knowing what’s possible in a technical sense during the design process, but knowing still doesn’t ease the process of deciding which possibilities you’ll use and won’t use :)

  18. [...] phpied.com — CSS Coding Conventions [...]

  19. Hi!

    Very good article, congradulations.

    I have one thig to add:

    For multiple selectors, I use it this:

    div#sidebar-left
    , div#sidebar-left input
    , div#sidebar-left select
    , ul#breadcrumbs
    , div#sidebar-right
    , .etc
    {
    font-size: 11px;
    }

  20. [continuing]
    I make it to dont foorget the commas and make it more readable.

    Learned with a firend that make BIG SQL querys at databases.

  21. [...] CSS Coding Conventions von phpied.com [...]

  22. Good article. I need to set-up practises and guidelines because we’re working with an external party to supply HTML/CSS. I’ll not bother about
    shorthands. But most of the rest, I’ll just place as “the rule”, untill they convince me otherwise. (c:

  23. [...] [RSS] The Net is Dead – Life Beyond the Buzz Marco is this cool guy, web dev from Netherlands. I “met” him through his comments on my CSS conventions post, which turned out to be a bit controversial at times. Marco was totally on my side. Seems like he’s pretty busy now and doesn’t post as much as he used to, but I’m sure he’ll be back. [...]

  24. [...] read more | digg story [...]

  25. [...] I was confounding myself with my stylesheets and the ill-mannered conventions I was applying to them. PHPied’s “CSS Coding Conventions” suggests some great conventions that have immensely improved my stylesheets. I especially like the cascading naming convention, dash separated, to improve selector readability.       [...]

  26. This won’t be very friendly when you’re in the dev phase, trying out different styles and admiring the results, but still interesting.

  27. [...] Find more suggestions on naming conventions at PHPied’s article CSS Coding Conventions. I linked to this article before, but it’s just so applicable and sensible that I must link again.       [...]

  28. If I can go back into a 3 year old document, and find the exact class or id I’m looking for in a few seconds, the time it took to develop a standard is worth it.

  29. [...] 13. CSS (link, link2, link3) [...]

  30. [...] http://www.phpied.com/css-coding-conventions/ [...]

  31. The link to this page under popular posts has a spelling error and returns a 404.

  32. Thanks Andreas, much appreciated!

  33. Hey Stoyan, I can’t say I agree with the short hand part fully, but after going through everyone’s comments and your reply on it I am convinced that it is pretty much one’s own decision. The rest is really useful. Although I follow most of these, it was good to see it written down.

  34. CSS “Cascading Style Sheets” LessoNs – WeB DesigN LessoN – - Web site : http://WWW.css-lessons.ucoz.com/index.html

  35. HI i need your help i really want to create my own website/web page but i dont know how to go about doing it so can you please help me out

  36. [...] [...]

  37. [...] CSS coding conventions [...]

  38. Here is a very complete an professional CSS Coding Style Convention (Standards Guidelines & Rules), find it here:
    http://www.nodewave.com/document/css-coding-style-conventions–standards-guidelines-rules

    This document give guidelines to improve development productivity with CSS, this by organizing code and making it very readable, and exchangeable among developers without a loss of productivity while “diving-in”.

  39. I got to your excellent article via stackoverflow, and the comment was made that putting the curly bracket on the next line, ie:

    .class-name
    {
    color: green;
    }

    has the advantage of much better readability if multiple selectors are specified, ie:

    .class-name p, .class-name span {
    color: green;
    }

    is not nearly so clear as:

    .class-name p,
    .class-name span
    {
    color: green;
    }

    as someone who, like you, prefers the bracket on the end of the line (primarily for the saved wasted vertical space), it made me wonder if I was wrong. Perhaps worth mentioning.

  40. I don’t think shorthands should be avoided, only few of them respectively a few variants of them.

    Compare:

    …{
    margin-left:2px;
    margin-right:2px;
    margin-top:2px;
    margin-bottom:2px;}

    …{
    margin:2px;}

    I don’t do much CSS (I’m more of a programmer), but I have no problem to remember the order of two of the other variants:

    …{
    margin:1px 2px;} // top and bottom margins are 1px, left and right 2px

    …{
    margin:1px 2px 3px 4px;} // top, right, bottom, left

    The first one is just horizontal before vertical, which is a common notation, the second ist just starting top and going clockwise. Indeed, the three-value-variant is somewhat asymmetrical and I avoid it.

  41. I like that someone at least made an attempt to discuss CSS conventions, which was conveniently left out of all my formal training in college. Convention emphasis was always placed on things like VB.Net, Java, C++, PHP, etc….

    I personally, am a fan of camel casing my IDs, classes, etc. For those unfamiliar (really?), thisIsCamelCasing or for a real world example “#mainNavigation”. I find them just as easy to read, and much easier to type than using hyphens, and A LOT easier to type than using underscores.

    A point people probably never considered is the ease of perusing text in a WYSIWYG’s using naming conventions. Hyphens slow down your text-cursor when cruising a line of text because it stops at each hyphen, whereas it skips right over camelCasing. Minor convenience, but I find it invaluable.

    I still use hyphens, but only to distinguish between a .class-subClass-subSubClass type of scenario.

    By the way, I agree with you on the shorthand notation. Every once in a while you run into syntax you seldom see and wonder w.t.h. is going on. I have some exceptions, I use shorthand for margin:Top Right Bottom Left; and for border:1px solid #HHEEXX.

    I don’t put spaces after colons, only after semi-colons between styles in a single pair.

  42. I wont accept the point,if you give spacing its gives readability,but at the same time it will increase the file size also.

    For a instance..

    Eg:
    #header{
    margin:10px;
    background:red;
    padding:10px;}
    .
    .
    .
    .

    #footer{
    margin:10px;
    background:green;
    padding:10px;}

    Instead of writing one by one,if you write in single line and compare the CSS file size.The below example file size will be less.

    Eg:
    #header{margin:10px;background:red;padding:10px;}
    .
    .
    .
    #footer{margin:10px;background:green;padding:10px;}

    if you write in single line and reduce the spaces then you can easily avoid the file size of the CSS.

  43. File size for a style sheet is an almost silly consideration given that it’s a text file that takes up virtually no space. Readability should be the primary concern. I favor putting everything on one line provided that you keep the line length short.

    You can do this by setting font family and some other standard settings on a more global level, such as in the body tag or on div tags that you know will encapsulate a number of others. This way you don’t have to so redundant. I think that I would add a space after the semi-colon, and would also put a blank line or two between blocks of related items. A comment here or there, probably wouldn’t hurt either.

    The issue of capitalization is an important one. In my own code, I’m all over the place on this and really need to get my act together.

  44. [...] Stoyan Stefanov: “The important thing to remember is—it’s not that important what exactly is a chosen standard or convention, the most important is that there is one. The rest, the details, is just common sense, and since ‘the common sense is not common to everybody’, pick whatever makes sense for you.” [...]

  45. [...] User Should also mention Less (http://lesscss.org/), and for coding conventions see this post : http://www.phpied.com/css-coding… or this http://meiert.com/en/blog/200805…As per usual: Pick your rules and stick to them.This [...]

  46. I quite agree with you mentioned, I think if css file is quite large, using shorthands can reduce the file size and improve performance. Having all opinion of that I already do the things you suggest.

  47. Sorry completely disagree with the naming convention

    .footer-copyright distracts far more then footerCopyright plus for people who copy and past try to double click on the first and then the second see what the difference is

  48. Its such as you learn my mind! You appear to understand so much approximately this, like you wrote the ebook in it or something. I believe that you can do with a few % to pressure the message house a little bit, but instead of that, this is magnificent blog. An excellent read. I’ll definitely be back.

  49. Free graphics, 3d, code snippets, PHP, HTML, JavaScript and more!…

    [...]CSS coding conventions / Stoyan’s phpied.com[...]…

  50. [...] process I have been looking elsewhere too.LinksWordPress CSS Coding Standard – WordPress CodexCSS Coding Conventions – phpied5 Tips for WordPress Theme Developers – theme.fm This entry was posted in [...]

  51. phương pháp giảm cân…

    [...]CSS coding conventions / Stoyan’s phpied.com[...]…

  52. @sriram: CSS compression (and javascript) has nothing to do with humans. You must write in the better way for you and use a compressor to stripe out white spaces and lines.

    About shorthand: I will never avoid them but the main problem I saw is that people write
    margin: 0 auto
    Instead of
    margin-left: auto; margin-right:auto;
    Thinking is the same and setting margin top and bottom to 0 without the real necessity or a check about what the value was before;

    Also, do really border don’t have a standard order? I don’t believe this is true but I have to check w3c to be sure. If you want to say that it worked anyway because they are subset and browser are smart that has nothing to do with standards.

    About 1 rule per line I have only one exception:
    float: left; display: inline;
    Display was a fix for ie6 and is disappearing but I was used to put on the same line (not on separate file) to make clear that it was redundant for compatiblity.

    @Marco Gomes: Love your idea for multiple lines

  53. Giong hat viet

    [...]CSS coding conventions / Stoyan’s phpied.com[...]…

  54. What’s up, after reading this awesome piece of writing i am also delighted to share my knowledge here with colleagues.

  55. […] your css, what the files should be called, etc. (Here are some at Snook.ca, Smashing Magazine, and phpied, for example.) The topic has been covered and for the most part is agreed […]

Leave a Reply