html5, css, javascript style guide and coding conventions

Download HTML5, CSS, JavaScript Style guide and coding conventions

If you can't read please download the document

Upload: knoldus-software-llp

Post on 14-Apr-2017

3.076 views

Category:

Software


0 download

TRANSCRIPT

HTML5, CSS, JavaScript Style guide and coding conventions

Priyanka Wadhwa

Software ConsultantKnoldus Software LLP

Agenda

Why we need coding Standards?

HTML5 coding conventions

CSS style guide

JavaScript Coding standards

What is a need for coding standards ?

ProblemWhen we learn a new language, we begin to code in a specific style. A style we want and not the one that has been suggested to us.Now what?

Can the other person actually read your code? Is it spaced out clearly?

Will he be able to work out whats happening without needing to look at every line?

Will he be able to know how and why are you commenting the work?

And many more questions may arise

Need for coding standards

SolutionCoding conventions are style guidelines for programming.A coding standards document tells developers how they should write their code. Instead of each developer coding in their own preferred style, they should write all code to the standards outlined in the document.Large projects need to be coded in a consistent style Not just to make the code easier to understand, but also to ensure that any developer who looks at the code will know what naming conventions say and what should he expect from the entire application.

HTML5 coding conventions

HTML5 coding conventions

HTML5 doctypeEnforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page.

Language AttributeA lang attribute is required to be specified on the root html element, giving the document's language.

specify a lang attribute on the root html element

Character encodingEnsure proper rendering of your content by declaring an explicit character encoding.

Internet Explorer compatibility modeInternet Explorer supports the use of a document compatibility tag to specify what version of IE the page should be rendered as.

CSS and JavaScript includes

/* */

HTML5 Coding conventions

UTF-8 is for chracter encoding. It is capable of encoding all possivle characters, defined by unicode.

UTF-8:UTF-8 is backwards compatible with ASCII. UTF-8 is the preferred encoding for e-mail and web pages1 byte: Standard ASCII

2 bytes: Arabic, Hebrew, most European scripts (most notably excluding Georgian)

3 bytes: BMP

4 bytes: All Unicode characters

UTF-16: capable of encoding the entire Unicode repertoire. UTF-16 is used in major operating systems and environments, like Microsoft Windows, Java and .NET.2 bytes: BMP

4 bytes: All Unicode characters

Attribute orderAs per the standards, we are required to follow the following order of HTML attributes -

class

id, name

data-*

src, for, type, href, value

title, alt

role, aria-*

Example link

HTML5 Coding conventions

Boolean attributesRequires no declaration.

1

Reducing markupProduce less HTML, avoid superfluous parent elements when writing HTML.

can be re-written as -

HTML5 Coding conventions

Some more basic standards -Always use the alt attribute with images. It is important when the image cannot be viewed.

Try to avoid code lines longer than 80 characters.

Spaces and equal signs - HTML5 allows spaces around equal signs. But space-less is easier to read, and groups entities better together.

Use the attributes name in lower case letters.

Close each and every HTML elements even empty HTML elements also..

HTML5 Coding conventions

CSS style guide

CSS style guide

Am I following the correct coding conventions here?

CSS style guide

Am I following the correct coding conventions here?

And what about me?

CSS style guide

Am I following the correct coding conventions here?

And what about me?

CSS style guide

Am I following the correct coding conventions here?

And what about me?

Let's find out the correct way of coding CSS , following the correct coding conventions.

CSS style guide

SyntaxUse soft tabs with two spacesthey're the only way to guarantee code renders the same in any environment.

When grouping selectors, keep individual selectors to a single line.

Include one space before the opening brace of declaration blocks for legibility.

Place closing braces of declaration blocks on a new line.

Include one space after : for each declaration.

Each declaration should appear on its own line for more accurate error reporting.

End all declarations with a semi-colon. The last declaration's is optional, but your code is more error prone without it.

Comma-separated property values should include a space after each comma (e.g., box-shadow).

CSS style guide

Don't include spaces after commas within rgb(), rgba() values. This helps differentiate multiple color values from multiple property values.

Don't prefix property values or color parameters with a leading zero (e.g., .5 instead of 0.5 and -.5px instead of -0.5px).

Lowercase all hex values, e.g., #fff. Lowercase letters are much easier to read.

Use shorthand hex values when available, e.g., #fff instead of #ffffff.

Quote attribute values in selectors, e.g., input[type="text"]. Theyre only optional in some cases, and its a good practice for consistency.

Avoid specifying units for zero values, e.g., margin: 0; instead of margin: 0px;.

CSS style guide

Declaration orderFollowing properties should be grouped together :

Positioning (position, top, right)

Box model (display, float, width, height)

Typographic (font, line-height, color)

Visual (background-color, border)

Misc (opacity)Positioning comes first because it can remove an element from the normal flow of the document and override box model related styles. The box model comes next as it dictates a component's dimensions and placement.

CSS style guide

Don't use of @importFrom a page speed standpoint, @import from a CSS file should almost never be used, as it can prevent stylesheets from being downloaded concurrently.

There are occasionally situations where @import is appropriate, but they are generally the exception, not the rule.

For instance, if stylesheet A contains the text: @import url("stylesheetB.css");then the download of the second stylesheet may not start until the first stylesheet has been downloaded. If, on the other hand, both stylesheets are referenced in elements in the main HTML page, both can be downloaded at the same time. If both stylesheets are always loaded together, it can also be helpful to simply combine them into a single file.

CSS style guide

Media query placement

Bundling the media query in a separate file is not preferable.

Decision to add it at the end of the CSS file or placing close to their relevant rule sets depends upon your CSS file.

CSS style guide

Single declarationsConsider removing line breaks for readability and faster editing. Any rule set with multiple declarations should be split to separate lines.

Single-line declaration

Multi-line declaration

CSS style guide

Shorthand notationStrive to limit use of shorthand declarations to instances where you must explicitly set all the available values. Common overused shorthand properties include:

padding

margin

font

background

border

Border-radiusOften times we don't need to set all the values a shorthand property represents.For example, HTML headings only set top and bottom margin, so when necessary, only override those two values. Excessive use of shorthand properties often leads to sloppier code with unnecessary overrides and unintended side effects.

CSS style guide

CommentsCode is written and maintained by people. Ensure your code is descriptive, well commented, and approachable by others. Great code comments convey context or purpose. Do not simply reiterate a component or class name.

CSS style guide

Class namesDo keep the following points in mind before giving class names to the HTML elements -

Keep classes lowercase and use dashes (not underscores or camelCase). Dashes serve as natural breaks in related class (e.g., .btn and .btn-danger).

Avoid excessive and arbitrary shorthand notation. .btn is useful for button, but .s doesn't mean anything.

Keep classes as short and succinct as possible.

Use meaningful names; use structural or purposeful names over presentational.

Prefix classes based on the closest parent or base class.

Use .js-* classes to denote behavior (as opposed to style), but keep these classes out of your CSS.Class to denote behavior : .js-calculate-priceSome good class names : .sequence { }, .sequence-header { }, .important { }Not so good class names : .s { }, .header { }, .red { }

CSS style guide

SelectorsKeep the following in mind before using nested CSS selectors -

Use classes over generic element tag for optimum rendering performance.

Avoid using several attribute selectors (eg., [class^="..."]) on commonly occurring components. Browser performance is known to be impacted by these.

Keep selectors short and strive to limit the number of elements in each selector to three.

Scope classes to the closest parent only when necessary (e.g., when not using prefixed classes).

CSS style guide

CSS quotationsUse single ('') rather than double ("") quotation marks for attribute selectors or property values.Do not use quotation marks in URI values (url()).@import url(//www.google.com/css);html { font-family: open sans, arial, sans-serif;}@import url(//www.google.com/css);html { font-family: 'open sans', arial, sans-serif;}

JavaScript coding standards

JS coding standards

Variable NamesUse of letters with camelCase in naming the variables.

firstName = Knoldus;

price = 9.90;

middlename = Softwares;

Spaces around operatorsSpaces should be used to differentiate operators and also after commas.

var x = y + z;

var values = [knoldus , software];

var values=[knoldus,software];

JS coding standards

Code Indentation4 spaces for indentation of code block -function toCelsius(fahrenheit) { return (5 / 9) * (fahrenheit 32);}* Do not use tabs for indentation Different editors may treat it differently.

Statement RulesSimple statements end with a semicolon. Like declaring a variablevar person = {firstName: Knoldus,lastName: Softwares,

};

JS coding standards

Complex/ compound statements must follow the following -

Opening bracket at the end of first line,

Space before opening bracket.

Closing bracket on a new line, without leading spaces.

And, complex statements doesn't end with a semicolon.

function tocelsius(fahrenheit) { return (5 / 9) * (fahrenheit - 32);}* same applies for the loop and conditional statements.

JS coding standards

Object Rules -

Placing opening brackets on the same as the object name.

Using colon plus one space between each property and its value.

No adding of comma at the last property-value pair.

Placing of closing brackets on a new line, without leading spaces.

Never forget to end an object with a semicolon.var person = { firstName: "Knoldus", lastName: "Softwares"};Short objects can be compressed and written in one line using the spaces only between their properties -var person = {firstName:"Knoldus", lastName:"Softwares"};

JS coding standards

Line length < 80 charactersIf a javascript statement does not fit on one line, then the best place to break it, is after an operator or comma.document.getElementById("knolx").innerHTML = "Hello Knolders.";

Naming ConventionsRemember to maintain consistency in the naming convention for all your code.

All variables and functions must be in camelCase.

Global variables and Constants to be written in UPPERCASE.

JS coding standards

Line length < 80 charactersIf a javascript statement does not fit on one line, then the best place to break it, is after an operator or comma.document.getElementById("knolx").innerHTML = "Hello Knolders.";

Naming ConventionsRemember to maintain consistency in the naming convention for all your code.

All variables and functions must be in camelCase.

Global variables and Constants to be written in UPPERCASE.

Should we use hyp-hens, camelCase or under_scores in variable names?

JS coding standards

Hyphens (-) HTML5 attributes can have hyphens (data-element, data-count).

CSS uses hyphens in property names (background-color, padding-left, font-size)

JavaScript names does not allow use of hyphens. As they can conflict with subtraction operator.Underscores ( _ )

Underscores (date_of_birth) are mostly used in databases or in documentation. So, we prefer not to go with using underscores.PascalCase

It is often used by C Programmers.CamelCase

This is used by javascript, jquery and in various JS libraries.

References

https://google.github.io/styleguide/htmlcssguide.xml

http://codeguide.co

http://www.w3schools.com/js/js_conventions.asp

http://www.w3schools.com/html/html5_syntax.asp

Thank you :)