Best Practices
Best Practices

The Golden Rule

All code in any part of the code base should look like a single person typed it, no matter how many people contributed.


HTML


  • Human Readable

    Code is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others.

  • HTML5 doctype

    Enforce standards mode in every browser possible with this simple doctype at the beginning of every HTML page.

    <!doctype html>
  • Syntax
    • Use soft-tabs with two spaces
    • Nested elements should be indented once (2 spaces)
    • Don't include a trailing slash in self-closing elements
  • Attributes
    • Attributes should be lowercase.
    • Always use double quotes ("), never single quotes.
    • Boolean attributes should be used without quoted values to avoid redundancy.
  • Attribute order

    HTML attributes should come in this particular order for easier reading of code.

    • id
    • class
    • data-*
    • for | type | href | src
  • HTML Comments
    • Section comments are separated from the previous block by one line, and should have one following line of space.
    • Prepend section headings with an equal sign (=), to make a Find operation easier.
    <!-- Component Name -->
    <div class="componentName">
      ...
    </div>
    <!-- ./Component Name -->

CSS


    • Use soft-tabs with two spaces
    • When grouping selectors, keep individual selectors to a single line
    • Include one space before the opening brace of declaration blocks
    • Place closing braces of declaration blocks on a new line
    • Include one space after : in each property
    • Each declaration should appear on its own line
    • End all declarations with a semi-colon;
    • Comma-separated values should include a space after each comma
    • Don't include spaces after commas in RGB or RGBa colors
    • Do not specify units for zero values, e.g., margin: 0; instead of margin: 0px;
    • Use shorthand hex values where available, e.g., #fff instead of #ffffff
    • Lowercase all hex values, e.g., #fff instead of #FFF
    • Quote attribute values in selectors, e.g., input[type="text"]
  • Declaration Organization
    1. Box (Display, Float, Position, Left, Top, Width, Height, Margin, Padding, etc.)
    2. Border
    3. Background
    4. Text
    5. Other
    .declaration-order {
      /* Positioning */
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      z-index: 100;
    
      /* Box-model */
      display: block;
      float: right;
      width: 100px;
      height: 100px;
    
      /* Typography */
      font: normal 13px "Helvetica Neue", sans-serif;
      line-height: 1.5;
      color: #333;
      text-align: center;
    
      /* Visual */
      background-color: #f5f5f5;
      border: 1px solid #e5e5e5;
      border-radius: 3px;
    
      /* Misc */
      opacity: 1;
    }
    .some-div { color: #222; }
    
    .some-other-div,
    .some-additional-div {
      margin: 0 auto;
      color: #222;
    }
  • General Formatting

    Use a new line for every block, list or table element, and indent every such child element to show heirarchy and improve understanding. This applies to elements nested in Sass as well.

    .print {
      display: block;
      margin: 0;
      padding: 0 7px;
      height: 30px;
      background: #4f799f;
      line-height: 30px;
    }
    
    .print:hover { background: #265a83; }
  • Avoid Qualifying ID and class names with type selectors

    // this is bad
    ul#example { color: #ff0; }
    div.error { color: red; }
    // this is good
    #example { color: #0f0; }
    .error { color: green; }

    p.s. ID's are bad for CSS, only use ID's for javascript hooks when necessary

  • Hexadecimal Notation

    For color values that permit, 3 character hexadecimal is preferred

    /* not recommended */
    color: #00ff00;
    /* recommended */
    color: #0f0;
  • !important
    Just don't do it.

    Use greater specificity to workaround using !important; -- you will be judged in the afterlife

  • Use the SMACSS Approach
    .componentName {
    
      Base {
      ...
      }
    
      Layout {
      ...
      }
    
      Module {
      ...
      }
    
      State {
      ...
      }
    
      Theme {
      ...
      }
    
    }
  • Commenting
    // File headers are commented thusly:
    
    /* ==========================================================================
        Component Name -- Version: 1.0.0.0 - Updated: MM/DD/YYYY
       ========================================================================== */
    /**
     * Helper class to truncate and add ellipsis to a string too long for it to fit
     * on a single line.
     * 1. Prevent content from wrapping, forcing it on a single line.
     * 2. Add ellipsis at the end of the line.
     */
    .ellipsis {
      white-space: nowrap; /* 1 */
      text-overflow: ellipsis; /* 2 */
      overflow: hidden;
    }
    /* Hints get styled like this */

Sass (or less or stylus, whatever! you choose)


  • File Organization
    • Mixins and variables go in scss/global/.
    • Styles related to components/modules/views go in sass/components/.
    • Sass and CSS from other projects goes in sass/vendor/.
    scss/
    ├── main.scss
    ├── globals/
    |   ├── _functions.scss
    |   ├── _grid.scss
    |   ├── _mixins.scss
    |   ├── _placeholders.scss
    |   ├── _var.scss
    ├── partials/
    |   └── component/
    |       └── _component.scss
    |       └── _component-theme.scss
    └── vendor/
        └── jquery.1.11.2.min.js
  • Main Stylesheet

    All files get compiled into the main.scss stylesheet, and should be scoped accordingly.

    The main.scss file serves as a "table of contents" and the @import directives should be listed with vendor dependencies first, then author dependencies and core stylesheets, then components.

    Organize the components imports in a manner that makes sense, in other words, group components with the component they extend or inherit from.

    /* Mixins and Variables */
    // All globals are combined in allGlobals.scss to reduce the nuber of updates necessary to add new files
    @import "global/allGlobals";
    
    /* Base */
    @import "partials/base";
    
    /* Layout */
    @import "partials/layout";
    
    /* Modules */
    
    @import "partials/colors";
    
    @import "partials/typography";
    
    @import "partials/helpers";
    
    @import "partials/lists";
    
    @import "partials/buttons";
    
    @import "partials/pagination";
    
    @import "partials/accessibility";
    
    @import "partials/forms";
    
    @import "partials/images";
    
    @import "partials/videos";
    
    @import "partials/modules";
    
    @import "partials/jumpTo";
    
    @import "partials/_prototype";
    
    @import "partials/_styleguide";
    
    /* Components */
  • Structuring Code

    @extends and @includes are likely to be overwritten by future elements, placing them at the top of the property list calls them out and avoids the beginning of a specificity war.

    • @extends should be grouped together at the top of the selector.
    • @includes should be grouped together after @extends.
    • Regular styles for the current selector should be after @includes.
    • Nested selectors appear last, with space seperating each block.
    • Nested selectors using & should appear above child (>) nested selectors.
  • Limit nesting to 3 levels and/or 50 lines

    Nesting selectors more than three levels deep and the code is at risk of being to reliant on HTML structure, overly-specific and difficult to understand.

    50 lines is reasonable length for keeping an entire block on a code editor screen without having to scroll.

  • Variabilize ALL THE THINGS!
    • Variabilize all colors.
    • Numbers (other than 0 or 100%) with strong meaning or frequent use should be variables.
    • Use hyphens (-) in variable names.
    • Name variables based on what they represent, not their values, e.g. $text-size-large instead of $text-size-24.
    • Colors, fonts, and base measurements are all great candidates for variables. If you find yourself writing a number other than 0 or 100% more than once, make it a variable.
    • Most variables should be stored in the _vars.scss partial; however, it's acceptable to define component specific variables in the component files.
    • In this case, the variables should be stored at the top of the file.
  • Comments

    Try to stick with standard CSS comments, but you can use the Sass style (//) comments for trivial comments or quickly debugging.


JS


  • Prefix all javascript-based selectors with js-. The idea is that you should be able to tell a presentational class from a functional class. Do it!


SEO

Only One h1 Tag Per Page

While technically we could load a page up with h1 tags, it's a bad SEO practice and can cause penalties.


Use Title Attributes with Links

Using a title="" attribute in your anchor elements will improve accessibility when used the right way.

It is important to understand that the title attribute should be used to increase the meaning of the anchor tag.


How Much Will A Reader Read?
"A sentence should contain no unnecessary words, a paragraph no unnecessary sentences, for the same reason that a drawing should have no unnecessary lines and a machine no unnecessary parts."
William Strunk, Jr.

ARIA & Accessibility


  • Making it possible to provide an enhanced user experience for people with disabilities when using internet applications with assistive technologies.

  • Landmark Roles

    banner - typically the "header" of the page

    <header role="banner" class="header"></header>

    navigation - any navigation list, typically the nav element

    <nav role="navigation" class="nav"></nav>

    main - the main content area

    <section role="main" class="main"></main>

    complimentary - information that is tangentially related to the main content

    <aside role="complimentary" class="aside"></aside>

    contentinfo - contains information about the parent document such as copyrights and privacy statements

    <footer role="contentinfo" class="footer"></footer>
  • Using alt Text Properly

    A few tips on how and when to use the alt attribute:

    • Use the alt attribute for any image that is used as content.
    • Use an empty alt atribute for any image that is decorative or not necessary for understanding the content of the page (alt=”“).
    • Make sure the description of the image is useful. For example, if the image is your logo your alt should be your company name and not “logo”

    The alt attribute is meant to help users using assitive techonology not miss any content, so make sure your text is helpful to anyone not seeing the image.

  • <.visually-hidden> - The Visually-Hidden class allows for 508 Compliance on an element needed for visually assisted users.