CSS Best Practices

Separate content from presentation in order to make your website accessible to all users and devices, increase the longevity of your website (you won’t have to touch you HTML to alter the page’s layout), and enable the creating of new pages without worrying about consistency of appearance or layout. (Note that i wrote this in 2004 and posted here in 2007, so some stuff may be archaic).

General CSS Rules

  • Build and test your CSS in Firefox (or Safari if you are working on a Mac).
  • Specify units for non-zero values, but not for zero values.
  • Don’t use quotation marks around paths/URLs when setting a background image or loading in an imported file
  • Try to avoid applying padding/borders and a fixed width to an element. Rather, apply padding to the parent element.
  • Minimize number of ID’s used
  • Minimize number of classes used
  • Don’t use anchors, instead use ID’s.
  • Sandbox your style declarations
  • Combine selectors.
  • Use good naming conventions
  • Control the browsers CSS: Start with a clean slate.
  • Declare relative font sizes instead of absolute.
  • Create classes for error handling named based on the error
  • Avoid !important.
  • Avoid in-line CSS
  • Code link pseudo-classes in this order: Link, Visited, Hover, Active.

Stylesheet Maintenance

  • Minimize and clean up your css
  • Organize your CSS file
  • There are pros and cons to using Multiple stylesheets

HTML Development

  • Separate Structure and Presentation
  • Use HTML structure
  • Encompass everything in an element.
  • Use HTML elements for their intented purpose:
  • Avoid excess code
  • Avoid meaningless markup
  • Case sensitivity

General CSS Rules

Build and test your CSS in Firefox or Safari if you are working on a Mac.

  • Do not look at it or test your code in other browsers, especially IE, until the code is complete, approved and validated. This way you will start with clean, standards-compliant code that you can alter for non-standards compliant browsers, rather hacking from buggy code to support good browsers
  • If developing in Safari, develop with embedded styles in the header, but launch with imported styles to eliminate potential caching issues.
  • @import or <link> the css. It is better to <link rel="stylesheet" type="text/css" ... > because using @import can delay the rendering of your page.
  • Use as few browser hacks as possible, and document them with comments. Try to use valid CSS filters instead of non-validating hacks

Specify units for non-zero values.

  • Zero is zero, so do don’t include a unit type. For all other cases, CSS requires you to specify units on all quantities such as fonts, margins and sizes. Example: margin: 0 4px 0 2em;

Don’t use quotation marks around paths/URLs when setting a background image or loading in an imported file

  • They are not required or necessary and they will freeze IE5 on the Mac.

Try to avoid applying padding/borders and a fixed width to an element. Rather, apply padding to the parent element.

  • Because of IE 6 (and lower) box-model issues, if you apply padding to the parent element instead of the child element, IE will render the same as standards compliant browsers.

Minimize use of ID’s:

  • By encompassing sections in a named outer div, you can generally stylize all the contained components without the use of classes.
  • Use IDs sparingly: IDs have to be unique on a page, so using them for structural elements means that you can only ever have one content block on a page. #mainnavigation li li a should suffice for a drop down menu link and can be overwritten with #mainnavigation li li li a if there are submenus.
  • With minimal use of ID’s one can still target almost any element on the page, while allowing ASP.net autogenerated code (which is “ID happy”) to have the freedom to put ID’s all over the page.
  • Combine your selectors and sandbox your declarations (see below)

Minimize use of classes

  • Only use classes on elements that have any chance of being repeated on a page and in different locations, if the element is going to exist in a predictable location cascade based on the parent div ID,

Don’t use anchors, instead use ID’s.

  • Less code with multi-purpose code. Instead of using <a name=”anchor”> give an id to the parent of where that anchor would fall. All ID’s need to be unique, but so do the named anchors, so you are actually saving code and avoiding the pitfall of the effects of a a:hover defined for actual links

Sandbox your style declarations

  • Limit the “reach” of style declarations by pre-pending the class name, such as #maincontent p{}.

Combine selectors.

  • Keeping your CSS light is important to minimize download times; as much as possible, group selectors and rely on inheritance.

Naming conventions:

  • Never use layout descriptives in class names. Rather, use functional names for your classes, avoid words that describe how they look or where they are located on the page. “mainnavigation” is better than “leftnavigation”. Use “.copyright” and “.pullquote” instead of “smallgrey” or “indentitalic”. Name classes/IDs based on function, not appearance. If you create a .smallblue class, and later get a request to change the text to large and red, the class stops making any form of sense. Instead use descriptive classes like
  • Always use intention revealing classnames: Its tempting to use short cryptic class names (.s, .lbl) but unless you keep a glossary up to date of your class names, you will forget what they do. You may also run into problems with older browsers that can occasionally confuse classnames that start the same (i.e. .err and .errors are sometimes confused)
  • Avoid using the same classname for different purposes. The cascade can be very powerful but sometimes there is a temptation to use the same generic classname in many places. If you don’t sandbox your Css well, you can run into troubles.
  • Always use the same classname for similar purposes: Becuase the cascade is so powerful, you should reuse a classname in different places when they represent the same concept.
  • Put your classname on the outer-most element. The child elements can be targeted with the parent elements classname or ID. Often you see things like:<div class="headertitle">...</div>
    <div class="headerdescription">...</div>
    <div class="headerlinks">...</div>

    It’s far better to write:

    <div id="header">
    <h3>...</h3>
    <p>...</p>
    <ul><li>...</li><ul>
    </div>

  • Although class and div names can include lowercase, uppercase, numbers and additional characters in class and div names, it is best to use all lower case letters and to for multiple word classes, separate the words with an underscore or use camel case. HTML attributes “id” and “class” are case sensitive!
  • Never use javascript method or property names as ID values. JavaScript DOM bindings specifies that javascript can index by id. For example, using “length” as an ID value on an element will cause headaches when using myObjects.length.

Start with a clean slate.

  • Create default page with no rendering; include this code but change color and font-family if necessarybody, div, dl, dt, dd, ul, ol, li, h1, h2, h3, h4, h5, h6, pre, form, fieldset, input, p, blockquote, th, td { font-family: Arial, Helvetica, sans-serif; color:#000000; font-size: x-small;}
    table{border-collapse: collapse; border-spacing:0;}
    fieldset, img{border:0;}
    address, caption, cite, code, dfn, em, strong, th, var{font-style: normal; font-weight:normal;}
    h1, h2, h3, h4, h5, h6 {font-size:100%;}
    q:before, q:after{content:'';}
  • If you select other fonts for display, you don’t need to declare default classes since the first declaration declares default classes for all necessary elements.

Declare relative font sizes instead of absolute.

  • Always declare font-sizes in percentages or ems for maximum usability, consistency, and accessibility. This will enable pages to grow organically when user chooses to make text larger or smaller. Ems are easier to control than pixels.

Create classes for error handling named based on the error:

  • Form error handling is a good place to use multiple classnames. As an example, if you have a form, fields are typically either required or optional and have an error or not. Use “error required”, “error optional, “error feedback” (for a total of 4 classes, instead of 6), etc. Don’t call the classes “rederror”, redbigerror, etc, because when coding new error messages it won’t be obvious to the programmers which class to use.

Avoid !important.

Avoid in-line CSS

  • Inline styles negates the power of CSS and should only be used for testing purposes, such as including style=”border: 1px solid #ff0000;” to identify box model quirks

Code link pseudo-classes in this order: Link, Visited, Hover, Active.

  • In your CSS, code the links in order of a:link, a:visited, a:hover and a:active. Some people remember this best by the mneumonic “LoVe HAte”. In the hover definition, include visited:hover to ensure your hover effect works on visited links.

Stylesheet Maintenance

Minimize and clean up your css

  • Use as little CSS as possible, remove styles and parts of styles not being used or that were experimented with in the design process.

Organize your CSS file

  • Introduce your stylesheets with comments and explanation of how the particular sheet fits in with other sheets and with the site.
  • Use a predictable format. Organize similar rules together and use comments before each section to help you keep track of things for future redesigns/updates.
  • Group your styles with short and precise labels via comments
  • Make sure to comment blocks of CSS appropriately, group like-selectors, and establish a consistent naming convention, white space formatting. Incase different developers are using different platforms to edit the CSS, it is best to use spaces instead of tabs for white spce. Also, it is helpful to have consistent property order, though this is one I don’t do.
  • Start with clearing all default values, as mentioned above: this will reduce redundancy. Follow this by global styles. Lastly include section specific styles. For example, declare default element values. Next create sections of code for each section of your document. Next come the content sections which I generally divide into #header, #navigation, #maincontent and #footer. Include all the layout for the various elements for each of these id’s that are site global within each section
  • After site-wide declarations grouped by section/ID, if there are different “page colors” or layout looks, include a section for each of the different looks. If a declaration is valid for all “looks”, include it in the declarations above. If a declaration is valid for a subset of looks only, first declare a section for the multiple subset looks. This should be followed by unique page sections.
  • Finally, declare “weird” effects that only effect a paragraph type, a link based on value, etc.

Multiple stylesheets

  • Multiple stylesheets are appropriate for large and complexly styled sites, however extra http calls should be minimized.
  • Make sure multiple style sheets are really worth while – a single long CSS file can at least be searched easily (“find all instances of h2″)
  • The base styles file contains CSS rules that can be applied on every page, more specific sheets based on section or page color schema.

HTML Development

Separate Structure and Presentation

  • The goal should be to only have one line of CSS on the entire page: the call to an external style sheet.
    The eventual goal should also be to have one line of JavaScript – the call to the external file, with no inline event handlers, but we haven’t covered that yet.
  • Use semantic HTML structure that have semantic meaning such as <strong> and <em>
    instead of <b> and <large>. To give emphasis to a title, or stylizing a p tag, use semantic mark up such as <h1> thru <h6>

Encompass everything in an element.

  • <div> and <span> have no intrinsic meaning. Encompass all text in appropriate elements: <h1> … <h6>, <p>, <cite>, etc.

Use HTML elements for their intented purpose:

  • Use <blockquote> for blockquotes. <li> for list items, <cite> for citations.
  • Use list items for lists of links. Remember, navigations are generally a list of links and it is appropriate to use lists.

Avoid excess code,

  • Instead of repeated <br /> and  <p></p> use margin and padding

Avoid meaningless markup

  • Instead of <b> and <i>, use <strong> and <em>

Case sensitivity

  • All HTML markup, JavaScript, and CSS should be lowercase. Event handlers should be written in all lower case: use onlick not onClick. (actually, they should be in your JS, not in XHTML, but if you’re going to use them, make sure they’re lowercase). Use <p>, not <P>. Attribute values should all be lower case as well, unless referring to a file name that includes other characters. File names and file extensions should also be lowercase (no rule on this, just easier to remember class names, file names, image names, etc. if you don’t have to worry about case.
  • If a header should be all-caps, code it in regular case as you would want to see it printed, and then transform the text to all uppercase with CSS text transformation.


This entry was posted in Best Practices, CSS (including hacks), Web Development. Bookmark the permalink.

14 Responses to CSS Best Practices

  1. Read through this, and got to the “Code link pseudo-classes in this order: Link, Visited, Hover, Active.” section, some people may have a much easier time remembering this as “LoVe HAte”. I know it has helped me ever since I read it somewhere. Great Article.

  2. Estelle says:

    Good point. I’ll add it up there just incase people miss the comments. Thanks

  3. cinxgler1 says:

    Hi, good article, it’s helped me a lot, but I’ve tried to include javascript via document.getElementById(‘id’).innerHTML breaking the script tags, but it doesn’t work, Do you know if there’s another way to include a javascript when I include the code using the innerHTML?

    Thanks in advance

  4. Lee Kowalkowski says:

    Where should link:focus go?

  5. Pingback: Confluence: Customer Operations

  6. Will says:

    Hi Estelle,
    I came across your site when I finally had enough of hacking CSS and decided to learn how to do it right. Very interesting tips you have noted, but where can I find out the justification for them, i.e. to help me understand better, is there a big CSS resource that actually covers ‘best practices’ in minute detail? I just need to understand why I should things the way I should.
    Thanks.

  7. sim says:

    Explain with examples

  8. Adrien says:

    Yo Estelle,

    Seems good but it lacks example, it’s a bit like wikipedia asking for references ;) !

    I’ll read ur advices anyway but it would be much more powerfull with examples and references.

    Thx!

    Chuss

    Good day!

    Ad

  9. Veera says:

    This article is really helpful. Also, I would like to add this tip:

    Keep a library of helpful CSS classes.

  10. David S says:

    When I got to the part on case sensitivity and saw your advice:

    “use onlick not onClick”

    That made reading the whole article worthwhile.

    Thanks for a laugh.

    DS

  11. Pingback: Confluence: Utviklingsrammeverk

  12. I came across your site when I finally had enough of hacking CSS and decided to learn how to do it right. Very interesting tips you have noted, but where can I find out the justification for them, i.e. to help me understand better, is there a big CSS resource that actually covers ‘best practices’ in minute detail? I just need to understand why I should things the way I should.
    Thanks.

  13. Pingback: JavaScript的陷阱 « Koubei UED

  14. Pingback: HTML, CSS & JavaScript Web Designer or Web Developer Interview Questions | Inspiration

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>