Front-end coding standards and best practices

What's it all about

This document will act as a guideline for front-end development in general. As the landscape of the web and the way people use it changes over time, so will these standards and best practices. Everyone is encouraged to contribute to this document, so it will be as concise and up-to-date as possible.

For whom

This document is mainly targeted at people that are themselves Front-end developers or are beyond the basics of front-end development in their skill set. If you are a beginner, junior, there are very good starting points online, like https://www.w3.org/community/webed/wiki/Main_Page This document can also be of interest to people that have dealings with front-end development, front-end developers and interface creation in general within Unit4. You'll learn a bit more about the natural habitat of front-end development.

Why standards? Why rules? Best practices?

  • To maintain a certain level of quality.
    This document provides the guidelines for that benchmark of quality.
  • To guarantee portability and continuity.
    So other people can work with and understand the code and its structure and maintain its consistency. And they will and can build upon that using the guidelines below.
  • To create robustness.
    The interface of the web application will be future proof and backward compatible across browsers, platforms and devices.

What is front-end development about?

Next to these 3 fundamentals our front-end development also takes learnings from these great concepts:

In the thought of the above concepts look for repeated design patterns and abstract them. Build these skeletons as base 'objects' and then add CSS classes onto these to extend their styling for specific contexts or circumstances.
Split a component into structure and skin. Build the structure of the component using very generic classes so that we can reuse that construct and then use more specific CSS classes to skin it up and add visual design.

General practices

Clean coding

Although there are tools, code sweepers, which will tidy up your handcrafted HTML or CSS, first of all writing legible code should become second nature. To preserve the uniformity of HTML, CSS and JavaScript, some rules have been set to follow.

Indentation and alignment

For all code languages, we require indentation to be done via tabs. For alignment spaces can be used. http://lea.verou.me/2012/01/why-tabs-are-clearly-superior/ And there should be no trailing whitespace.

HTML

Lorem ipsum dolor

Donec luctus tortor nisi, vulputate malesuada metus...

Code commenting

There is a whole spectrum between no comments, verbose and heavily formatted (With ASCII art) commenting. Commenting in general is encouraged and even obligatory to a certain extend. Inline commenting is also a way to document the intention of the code. Comments have to be removed outside of development envrironments as they do add some overhead to the code.

Readability vs Compression

Readability is generally preferred over compression as it comes to maintaining files. And regarding portability, anyone new to the (web) application can understand the code faster. This is also beneficial for the continuity, as the code will be easier to build upon.

Server-side processing will minify and compress any static front-end files like JavaScript and CSS files. This is also the preferred process on staging and production environments.

Protocol

Omit the protocol portion (http:, https:) from URLs pointing to images and other media files, style sheets, and scripts unless the respective files are not available over both protocols.
Omitting the protocol, which makes the URL relative, prevents mixed content issues and results in minor file size savings.

HTML

CSS

.block {background:url("//www.unit4.com/images/block.png");}

Validity

The front-end code generally has to be valid which means that it is according to the standards and specifications set by W3C. This is both true for HTML and CSS. But 100% valid code is not a goal, but validation certainly helps to write more maintainable sites as well as debugging code. W3C - Why Validate?. Online tools are also provided by W3C to check if your code validates. These can be found in the Appendix Checks and validation section.

Language

UNIT4 is a global company and that means that English is the language of choice for internal communication, especially for documentation. So use English in your coding, for your variables, CSS class names, inline commenting, etc. To be even more specific use US-English. Also when using dummy text within your markup, use English, when not using Lorem ipsum.
Use a spell checking utility if you are uncertain what you have written is correct. This kind of checking should also be part of the code review process.

Markup

The basic component of every web page is tag-based markup language of HTML. Markup defines the structure and outline of a document and offers a structured content. Markup is not intended to define the look and feel of the content on the page beyond rudimentary concepts such as headers, paragraphs, and lists.

HTML5

HTML5 is the newest version of HTML and XHTML. For all our projects we will use the HTML5 doctype.

HTML

<!DOCTYPE html>
<html>
...
</html>

General guidelines

The following are general guidelines for structuring your HTML markup and some on specific elements and their attributes.

  • Items in list form should always be housed in a ul, ol, or dl, never a set of div's or p's.
  • Don't use HTML tables for layout purposes (Except when creating markup for Emails).
  • Use thead, tbody, tfoot, th tags and the scope attribute (about scope) when appropriate.
    Also keep accessibility in mind and add the right role attribute (Using WAI-ARIA in HTML) to the elements.

    HTML

    Weekday Date Quantity
    Mon 04/21 12
    Tue 04/22 45
    Wed 04/23 23
    Total 80
  • Every form field needs a <label> element. The "for" attribute of the label needs to be set and matched with the "id" attribute on the input so it's associated with that form element. This also means that every form element has to have an "id" that is unique to the page.

    HTML

    										
    										
  • Do not use the size attribute on your input fields. Instead use CSS width.
  • Forms should take advantage of the new HTML5 input types where they make sense to do so. But do take into consideration that these new types render differently across browsers, platforms and devices. HTML5 input types
  • Use the HTML5 placeholder attribute for input fields and text areas (Backwards compatibility for legacy browsers could done with a JavaScript polyfill).
  • All attribute values of markup tags should be quoted. Use double quotes.

    HTML

    										

    Lorem ipsum dolor...

  • Don't use breaks <br \> just to make space in your layout, or to separate natural components, or to create lists.
  • Although it is unnecessary according to the HTML5 spec, use XHTML self-closing style for elements.

    HTML

    ...
    <input type="text"  name="name" />
    <img src="path/to/img" alt="Alt text" />
    ...
  • Define the width and height attributes of an image. This will help avoid unnecessary repaints and reflows during rendering.
  • An image should almost always have a an alt attribute providing alternative information, especially for those visually impaired users (Also see the Accessibility section) or those users that have turned off the image support or don't have image support. The alt text should describe what the image is about.

    HTML

    <img src="img/logo_unit4.svg" alt="The Unit4 Logo" />
  • Use the title attribute on a link when it is relevant. It is there to provide additional information. Make use of it, but do not duplicate the content of your link.

    HTML

    <a href="http://www.lipsum.com/" title="The complete Lorem ipsum text can be found here">Lorem ipsum</a>

Email

Writing markup for emails is a whole other game than creating it for the WWW, for example the use of tables as a means of layout[11]. The rendering behaviour of email clients can vastly differ between them, and is the sum of device, platform, client and provider.
Basic rules for robust email markup are laid down in Campaign Monitor's Coding your Emails. A summary of email client quirks and tips can be found at Emailology. The different versions of Outlook of the past decennium can also be a challenge, as it uses the notorious Word rendering engine, Email on Acid has a good document with tips and guidelines on coding for Outlook. A special mention are background images as they are badly or not supported by some email clients. Campaign Monitor has a tool, www.backgrounds.cm to generate bulletproof markup to make these possible.

CSS

CSS is where front-end defines the look and feel of the application: The presentation.

Placement

References to CSS files should be placed in the head of the document, so the page renders progressively. (JavaScripts should be placed at the end of the page) Google Pagespeed - Move CSS to Head

HTML

<head>
...
<!-- CSS -->
<link rel="stylesheet" href="main.css" media="all">
</head>

Combine all CSS in a single CSS file (Like for example in main.css as above), be it by hand or through an automated build script with respect to the source order.

Normalizing

Normalizing makes browsers render all elements more consistently and in line with modern standards. It precisely targets only the styles that need normalizing. This is different from resetting CSS.
For every project we use the latest release of normalize.css from Nicolas Gallagher.
Include the reference to the minified normalize style sheet before any other style sheets.

HTML

									

Box sizing

The box-sizing should be reset to border-box for every element. This allows to set widths more easily to elements that also have padding and borders.[7]

CSS

html {box-sizing:border-box;}
*, *:before, *:after {box-sizing:inherit;}

Source order

Globally the main style sheet can be partitioned into the following sections:

  1. Elements – unclassed h1, unclassed ul etc.
  2. Objects and abstractions — generic, underlying design patterns.
  3. Components/modules – full components/modules.
  4. Contextual components/modules – components/modules in their context, on specific pages for example.
  5. Media queries - possibly responsive media query and/or print media query.
  6. Helper classes.
  7. IE classes (and possibly other browser specific CSS declarations).

Naming convention

A naming convention is useful to make the code more strict, transparent and more informative, serving the principles of robustness, continuity and portability.

When creating CSS class names:

  • Use all lower case letters.

    CSS

    .nav-main {margin:0 1.7%;}
  • Mostly use dashes as they serve as natural breaks in related class.

    CSS

    .btn {padding:5px 10px 5px 10px;}
    .btn-cancel {background-color:rgb(190,190,190);}
  • Use meaningful names and use structural or purposeful names over presentational (Some exceptions are tolerated within for example in a set of "helper" classes. But .grey {background-color:rgb(165,165,165);} would be considered toxic code).
  • Do not use CamelCase style.
  • js- prefix is solely a JavaScript hook CSS class. It should never be referenced in the CSS.
  • the state- prefix is a bridge class between CSS and JavaScript as it can be used by both. Mostly these state- CSS classes are controlled (behaviour) from the JavaScript and the containing element styled (presentation) by the CSS definition of that class.

Formatting

Although every developer has his own preferred method of formatting CSS, a few guidelines are set to preserve some CSS code consistency. Formatting can be divided into micro (At CSS declaration level), meso (At CSS code grouping level) and macro (At the CSS code organisational level)

CSS micro formatting

  • Each selector should be on its own line, ending in either a comma or an opening curly brace.

    CSS

    nav a:hover,
    nav a:focus,
    nav a:visited {color:rgb(34,226,68);}
  • Child styles get an additional indenting. That allows for hierarchical scanning and organization and makes (for some people) an easier-to-read style sheet.

    CSS

    nav {float:left;}
    	nav li {display:inline;}
    	nav a {color:rgb(51,51,102);}
  • For legibility of CSS selectors use a space before the opening curly brace { and before and after special combinators like, child >, adjacent sibling + and general sibling ~. When formatting declaration on a single line, use a space between declarations.

    CSS

    nav > ul {float:left;}
    nav ~ li {display:inline; border-top:1px dotted rgb(204,170,221);}
    nav ul + li {border-top:none;}
  • rgb(a) notation of colors is preferred over hexdecimal(HEX) color notation or color names like White or Red.

    CSS

    .comp-address {color:rgba(192,192,192,0.65);}
  • Don't include spaces after commas within rgb(), rgba(), hsl(), hsla(), or rect() values. This helps differentiate multiple color values (comma, no space) from multiple property values (comma with space).

    CSS

    .message .inline .error {color:rgb(221,64,64);}
  • Quote attribute values in selectors. Use double quotes.

    CSS

    input[type="radio"] {margin:5px 5px 0 0;}
  • Quote selector values of url part. Use double quotes.

    CSS

    .intro {background-image:url("images/bg_xl.png");}
  • Do not specify units for zero values.

    CSS

    nav ul {margin:0;}

Declaration order

Although there are several tools nowaday, it is good practice to use an order and a basic grouping of declaration properties.
CSS property groups could be: Positioning, Box-model, Typographic, Visual. This also helps when moving towards and introducing a front-end theme architecture in your application.

Browser specific CSS declarations

Any specific CSS declaration that only targets a certain browser should be isolated from the standards compliant set of CSS. This CSS code also has a predefined place in the CSS document source order. Isolation can be achieved by:

  • Namespacing - Adding a custom CSS class can set this declaration apart.
  • Client sniffing - Several techniques are available, server or client side with a wide range of success. Sometimes combined with device detection.
  • Browserhacks - Although browserhacks are not allowed! They could be used as solution in a temporary or last resort situation.

Internet Explorer

Because the use of different versions of IE is still widespread and our standard support for IE used to go back to IE8 (Internal standards for browser support) we use some things to accommodate for legacy IE versions if the project still needs support for these. Microsoft has annouced to change their support strategy for IE and will end active support for any other version then the latest version of IE by the beginning of 2016 (Stay up-to-date with Internet Explorer, Internet Explorer Support Lifecycle Policy FAQ).

  • To prevent IE from switching to unhelpful modes we add this to the markup:

    HTML

    The best practice is an X-UA-Compatible HTTP Header, it has to be configured server-side[9].
  • Every HTML document uses these conditional statements so it is possible to target a specific IE version or a set of IE versions and even a class when the browser is not of the IE family notie.
    This method only supports IE versions until IE9[10].

    HTML

    <!DOCTYPE html>
    
    
    
    
     <html class="no-js notie"> 
  • To enable the support for media queries and HTML5 elements in legacy IE versions, HTML5Shiv is used. This is done by adding a conditional statement and linking the HTML5Shiv library.

    HTML

  • When testing your work in IE start with the latest version and work your way back.
  • The single most important thing you need to know about fixing bugs in IE is giving an element "Layout". This will fix 99% of IE rendering bugs.
    The other 1% will most likely be related to position:relative; or floats. Use zoom:1 as a trigger for whatever IE versions need it.

    CSS

    										.ie7 nav li a {zoom:1;}
    The Internet Explorer hasLayout Property
  • Filters are "special features" in CSS for IE, they can slow down the page though, so use sparingly.

CSS in email

CSS support in email clients is somewhat erratic at times. An email client can strip out your finely crafted CSS or don't support basic CSS2.1 features. To get your head around this Campaign Monitor has a detailed overview of what is supported by different email clients: The Ultimate Guide to CSS.

Media queries

To deliver specific styles to different devices we use media queries. Depending on the requirements of the project several media queries can be incorporated in the CSS. One that is always used is the media query for standard print styles.

CSS

@media print {
	a,
	a:visited {text-decoration:underline;}
	
	...
}

CSS3

CSS3 provides great new features, and we encourage using them, but the same as with HTML5, keeping backwards compatibility and progressive enhancement in mind. Making pages look identical is not the aim, just don't rely on a CSS3 feature for an important feature of a page. As a rule of thumb treat CSS3 as visual rewards for capable browsers. In some cases there are (HTML5/CSS3) polyfills that can make legacy browsers behave like modern ones. But only use these if they perform well enough.

Best practices

This is a diverse list of conventions, best practices and guidelines in no particular order.

  • As mentioned in the first section of this document, we adhere to separation of content and presentation (more widely recognized mostly as "design" or "styling"), so inline styling is generally not tolerated (Except for example when coding CSS for email clients that need to be supported). In the case of setting style properties dynamically through JavaScript, use specific CSS hooks to do so.

    HTML

    									
    ...
    Building A Relationship Between CSS & JavaScript
  • Use a "multi-class" naming pattern to modify your components. It is a scalable pattern and easier to make tweaks in different contexts.

    CSS

    									.message {/* basic message component styles */}
    									.message.box {/* message type styles */}
    									.message.error {/* error message specific styles */}

    HTML

    									
    Something has happened...
  • The !important declaration should be avoided, unless absolutely necessary. It is okay to use !important on helper classes.
    !important CSS Declarations: How and When to Use Them
  • Try to avoid absolute positioning. In some cases it can be helpful and useful, in which case it's valid to use.
  • Code to a standards-compliant browser first (Or the one that is close), then fix issues in (legacy) IE versions or any other browsers that score poor on web standards (For example the Web Standards Project Acid Tests) and that you need to support.
  • No CSS (or browser) hacks are allowed!
  • Use all vendor prefixes if they are still needed for the browser set you are supporting. Put them in alphabetical order with the prefixless version last.

    CSS

    nav a:hover {
    	-moz-transform:scale(1.3);
    	-ms-transform:scale(1.3);
    	-o-transform:scale(1.3);
    	-webkit-transform:scale(1.3);
    	transform:scale(1.3);
    }
  • Almost anytime when you use the :hover pseudo class, also define the :focus pseudo class in the declaration you have made [6].

    CSS

    									button:hover,
    									button:focus {color:rgb(238,64,64);}
  • In shorthand notation [8] use the 4-value syntax or single value syntax.

    CSS

    									.intro {margin:0 0 1em 0; padding:0;}
    Try not to use 2 and 3-value shorthand syntax as it does not benefit the legibility of the code, also remember that excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects (And goes against the portability and continuity principle). This also falls in the category of micro optimizing css which should be avoided as minifying and compression scripts tend to do a better job.

Debugging

If you run into a CSS problem take code away before you start adding more in a bid to fix it. The problem exists in CSS that is already written, more CSS is not the right answer!
Delete chunks of markup and CSS until your problem goes away, then you can determine which part of the code the problem lies in.
It can be tempting to put an overflow:hidden; on something to hide the effects of a layout quirk, but overflow was probably never the problem; fix the problem, not its symptoms.

There are quite a few tools nowadays that can help you out if you need to debug anything interface related. Check the Appendix Tools - Debugging section.
Debugging email CSS comes down to basically testing your email, as there are no tools for it.

JavaScript

JavaScript enhances the user experience and behavior of the page.

Development of all our applications uses a mix of native JavaScript and jQuery. Always use a trusted third-party CDN (For example: Googles CDN service) to include jQuery as well as a local fallback should the CDN not be available. A CDN is beneficial for the performance of the application, as it provides decreased latency, fewer connections to the applications environment and possible better caching as the users may already have the files from other sources or recurring use.

The CDN URL needs to be "protocol-less", without http or https, as it is the best way to reference third party content that is available via both HTTP and HTTPS.

Plugins

JavaScript / JQuery Plugins should be added to the dedicated project's plugin.js file and only if necessary be included as a separate JS file, as that would increase the number of page requests, which is detrimental to performance as it increases page requests [4].

General guidelines

  • We rely on the JQuery Core Style Guidelines
  • Also take into account the W3C JavaScript best practices.
  • Adhere to the general principles and approach of Unobtrusive JavaScript. The before mentioned separation of functionality from presentation and content is also a big part of this.
  • There are several code validation tools for JavaScript that will locate some of the common mistakes, best practices outlined in the documents above, or just help with debugging code or finding that typo. Before adding your code to the codebase of a project, use them!
  • Don't use inline event handlers, inline or embedded JavaScript.
  • Keep style in CSS, use dedicated CSS classes as JavaScript hooks. Using the js- prefix is good practice to join these type of CSS classes in their own namespace.
  • Vanilla JavaScript mostly outperforms JQuery, always write and try to choose the best performing code. Code performance can be tested and a lot of use cases can be found at jsPerf — JavaScript performance playground.
  • Write meaningful comments in your code. This helps to reduce the time spent troubleshooting or debugging JavaScript functions.

JavaScript Patterns

For better JavaScript it is best to use certain scripting patterns. Stoyan Stefanov has written about these here.

Accessibility

Unit4 has no official guidelines for compliance with any standards regarding accessibility.
In the Appendix Checks & validation section are some tools to check the accessibility of web applications.

Appendix Checks & validation

Use them frequently, they give invaluable insight or point you to that hidden typo.

Online tools

(The tools below almost all have also in browser counterparts in the form of plugins/extensions)

Appendix Tools

It's not about the tools, but how you use them...

Code editors

Our development environment is based around Microsoft servers and tools, so MS Visual Studio is the obvious choice. But you're free to choose your own code editor or IDE, as long as you follow the guidelines laid out here and produce front-end code that complies with the Unit4 guidelines.

Code formatting

These tools can help out while creating new code, formatting existing code ,some general code sweeping. They can upgrade the quality of your code or check the quality of existing code.

  • CSS Comb, format CSS & SCSS files
  • Recess, the CSS code formatter developed by Twitter

Debugging

Every project or browser can have its own peculiarities, so inevitably you spend some time debugging code. These in situ tools will make it possible:
(Some of the mentioned tools below are available for multiple browsers, but only mentioned for Firefox here.)

  • Firefox:
    Firebug, before Firefox had its build in developer tools, Firebug was the tool of choice for debugging.
    Page Speed, analyze and optimize your website with this tool to check for web performance best practices.
    Developer toolbar, a set of handy tools.
    YSlow, makes an audit and analyses your website or application for performance issues.
    User Agent Switcher, spoof the user agent in you browser so you can trick the website in thinking you are using a different device, platform or browser. An updated User agent list XML file can be downloaded here.
  • Safari: Web Inspector
  • Google Chrome: Developer Tools
    Host a powerful set of tools to examine, debug and test your application. New features or tools can be added, for example Accessibility developer tools by Google accessibility.
  • Opera: Dragonfly
  • Internet Explorer 8-11: Developer Tools, DebugBar

Appendix Review

Code reviewing is one of the key elements within any (web) application development process as it ensures quality and minimizes risks by identifying bugs and defects. It also encourages collaboration and results mostly in more maintainable code. This section will only focus on the reviewing of front-end code and not the user interface in a broader sense as that would also include incorporating user experience, visual & interaction design.

In general

Code reviewing is one of the last stages within a development process, (also when a project is under time pressure) try to adhere to these best practices:

  • Peer code review means being reviewed by someone of equal or greater skill.
    As should be common sense, code review cannot work when a junior reviews a senior’s code.
  • Review fewer than 200-400 lines of code at a time.
    After going through so many lines of code, you will not filter out the bugs anymore.
  • Take on less than 300-500 lines of code per hour.
    Reviewing too fast will make you overlook mistakes.
  • Take enough time for a proper, slow review, but not more than 60-90 minutes.
    Effectiveness after an hour of any task drops significantly.
  • Checklists substantially improve results for both authors and reviewers.
    On these checklist can be common mistakes (A checklist for front-end coding still has to be made, but will have the most common mistakes and omissions in code on it.)
  • Verify that defects are actually fixed!
    Check if the mistakes, bugs are fixed/done after you have found and documented them.
  • A good code review culture must be nurtured and promoted.
    Code review is also about learning, growing and communication. It must be promoted positively by management to survive.

Are you reviewing front-end code?

Producing good code comes with experience, producing great code comes when you sit down with a peer and review it. So you are about to review front-end code, which basically means that you have check the given code against all that is in these standards and best practices. To do so here are some pointers:

  • Use the tools from the Appendix Checks & validation section to verify the code.
  • Use the DRY (Don't repeat yourself) method. Look for areas that are repeated or can be optimized by simplifying. But this does for example not mean that you should go and start combining CSS selectors.
  • Take a step back and look at the project as a whole and take on the performance of the web application. You can use Pagespeed as an analysis tool and have a look at Google's Web Performance Best Practices
  • As a final note: It's easy to get defensive when you are in the trenches and an outsider comes in and gives advice. It's important to get constructive criticism so you can battle test your work.

Appendix References and Resources

Front-end development has really come into bloom the last couple of years and a lot of great articles, books and knowledge in general has been published. Some of this has been at the basis of this document and are referenced here. Also some important resources are mentioned below for anyone that is into front-end development.

References

  1. W3C - HTML Design Principles
  2. Google HTML/CSS Styleguide
  3. Unit4 UX Center Styleguide
  4. High Performance Web Sites: Rule 1 – Make Fewer HTTP Requests
  5. Google JavaScript Styleguide
  6. Whenever you use :hover, also use :focus
  7. Paul Irish: * { Box-sizing: Border-box } FTW
  8. MDN - Shorthand properties
  9. How to use X-UA-Compatible
  10. Internet Explorer - About conditional comments
  11. The Tyranny of Tables: Why Web and Email Design are So Different

Resources

  • Paul Irish has contributed a lot to the front-end community (HTML5Boilerplate, Modernizr.js etc.) and continues to do so. Follow his front-end feed to keep up-to-date with everything front-end.
    Paul Irish Front-end feed
  • YSlow is still one of the best tools (Together with Pagespeed by Google mentioned in the review section) that was created by Yahoo!'s Exceptional Performance team. Read more about the best practice rules regarding web performance:
    Web performance best practices
  • The relentless posting of Chris Coyier makes it an obligatory read once a week. Also it is a great backlog of articles, discussions and snippets
    css-tricks.com
  • We all want the use the cutting edge features of CSS3, SVG, etc. but just check the browser support upfront at
    caniuse.com

Conferences

Conferences are a great way to get inspired, exchange knowledge and educate yourself on anything that plays a role in the front-end realm now or in the future.

Contribute

You want to contribute to this document? You can! Did you see a typo? Want to write some more on JavaScript? The latest released version of this document can always be found at http://front-end.unit4.is/. The development version resides in the Front-end Team Foundation Collection and can be obtained by connecting to the TFS server. If you don't have access, contact the TFS administrator.