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.
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...
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.
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.
-
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.
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.
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:
- Elements – unclassed
h1, unclassed ul etc.
- Objects and abstractions — generic, underlying design patterns.
- Components/modules – full components/modules.
- Contextual components/modules – components/modules in their context, on specific pages for example.
- Media queries - possibly responsive media query and/or print media query.
- Helper classes.
- 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.
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:
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.
-
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.
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.
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.
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.
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.
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.