SlideShare ist ein Scribd-Unternehmen logo
1 von 37
HTML5, CSS, JavaScript
Style guide and coding conventions
HTML5, CSS, JavaScript
Style guide and coding conventions
Priyanka Wadhwa
Software Consultant
Knoldus Software LLP
Priyanka Wadhwa
Software Consultant
Knoldus Software LLP
Agenda
● Why we need coding Standards?
● HTML5 coding conventions
● CSS style guide
● JavaScript Coding standards
● Why we need coding Standards?
● HTML5 coding conventions
● CSS style guide
● JavaScript Coding standards
What is a need for coding standards ?
Problem
When 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 what’s 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
Solution
Coding 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 doctype
Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at
the beginning of every HTML page.
<!DOCTYPE html>
<html>
<head>
</head>
</html>
● Language Attribute
A lang attribute is required to be specified on the root html element, giving the document's language.
<html lang=”en-us”>
<!→-→-->
</html>
● Character encoding
Ensure proper rendering of your content by declaring an explicit character encoding.
<head>
<meta charset=”UTF-8”>
</head>
● Internet Explorer compatibility mode
Internet Explorer supports the use of a document compatibility <meta> tag to specify what version of
IE the page should be rendered as.
<meta http-equiv=”X-UA-Compatibile” content=”IE=Edge”>
● CSS and JavaScript includes
<link rel='stylesheet' href='guide.css'>
<style>/* …… */</style>
HTML5 Coding conventions
● Attribute order
As 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-*
<a class=”….” id=”…..” data-toggle=”model” href=”#”>
Example link
</a>
<img src=”...” alt=”...”/>
HTML5 Coding conventions
● Boolean attributes
Requires no declaration.
<input type=”text” disabled>
<input type=”checkbox” value=”1” checked>
<select>
<option value=”1” selected>1</option>
</select>
● Reducing markup
Produce less HTML, avoid superfluous parent elements when writing HTML.
<span class=”avatar”>
<img src=”...”>
</span>
can be re-written as -
<img class=”avatar” src=”...”>
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
Syntax
● Use soft tabs with two spaces—they'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"]. They’re only optional in some
cases, and it’s a good practice for consistency.
● Avoid specifying units for zero values, e.g., margin: 0; instead of margin: 0px;.
CSS style guide
● Declaration order
Following 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 @import
From 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.
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 declarations
Consider 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 notation
Strive 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-radius
Often 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
● Comments
Code 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 names
Do 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-price
Some good class names : .sequence { … }, .sequence-header { … }, .important { … }
Not so good class names : .s { … }, .header { … }, .red { … }
CSS style guide
● Selectors
Keep 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 quotations
Use 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 Names
Use of letters with camelCase in naming the variables.
✔ firstName = “Knoldus”;
✔ price = 9.90;
✗ middlename = “Softwares”;
● Spaces around operators
Spaces 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 Indentation
4 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 Rules
Simple statements end with a semicolon. Like – declaring a variable
var 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 characters
If 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 Conventions
Remember 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 characters
If 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 Conventions
Remember 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 :)Thank you :)

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Introduction to CSS3
Introduction to CSS3Introduction to CSS3
Introduction to CSS3
 
SASS - CSS with Superpower
SASS - CSS with SuperpowerSASS - CSS with Superpower
SASS - CSS with Superpower
 
Css ppt
Css pptCss ppt
Css ppt
 
Html5 and-css3-overview
Html5 and-css3-overviewHtml5 and-css3-overview
Html5 and-css3-overview
 
Introduction to css
Introduction to cssIntroduction to css
Introduction to css
 
Cascading Style Sheet
Cascading Style SheetCascading Style Sheet
Cascading Style Sheet
 
CSS Basics
CSS BasicsCSS Basics
CSS Basics
 
CSS - OOCSS, SMACSS and more
CSS - OOCSS, SMACSS and moreCSS - OOCSS, SMACSS and more
CSS - OOCSS, SMACSS and more
 
Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)Introduction to Cascading Style Sheets (CSS)
Introduction to Cascading Style Sheets (CSS)
 
Css Specificity
Css SpecificityCss Specificity
Css Specificity
 
CSS
CSSCSS
CSS
 
HTML CSS JS in Nut shell
HTML  CSS JS in Nut shellHTML  CSS JS in Nut shell
HTML CSS JS in Nut shell
 
CSS INHERITANCE
CSS INHERITANCECSS INHERITANCE
CSS INHERITANCE
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
 
CSS Introduction
CSS IntroductionCSS Introduction
CSS Introduction
 
Javascript
JavascriptJavascript
Javascript
 
CSS3 Media Queries
CSS3 Media QueriesCSS3 Media Queries
CSS3 Media Queries
 
Css lecture notes
Css lecture notesCss lecture notes
Css lecture notes
 
Basic-CSS-tutorial
Basic-CSS-tutorialBasic-CSS-tutorial
Basic-CSS-tutorial
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
 

Andere mochten auch

Andere mochten auch (20)

Functional programming in Javascript
Functional programming in JavascriptFunctional programming in Javascript
Functional programming in Javascript
 
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdomMailchimp and Mandrill - The ‘Hominidae’ kingdom
Mailchimp and Mandrill - The ‘Hominidae’ kingdom
 
Introduction to BDD
Introduction to BDDIntroduction to BDD
Introduction to BDD
 
Deep dive into sass
Deep dive into sassDeep dive into sass
Deep dive into sass
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State Machine
 
Mandrill Templates
Mandrill TemplatesMandrill Templates
Mandrill Templates
 
Fast dataarchitecture
Fast dataarchitectureFast dataarchitecture
Fast dataarchitecture
 
Introduction to Quasiquotes
Introduction to QuasiquotesIntroduction to Quasiquotes
Introduction to Quasiquotes
 
Introduction to Knockout Js
Introduction to Knockout JsIntroduction to Knockout Js
Introduction to Knockout Js
 
Lambda Architecture with Spark
Lambda Architecture with SparkLambda Architecture with Spark
Lambda Architecture with Spark
 
Cassandra - Tips And Techniques
Cassandra - Tips And TechniquesCassandra - Tips And Techniques
Cassandra - Tips And Techniques
 
Introduction to Apache Cassandra
Introduction to Apache Cassandra Introduction to Apache Cassandra
Introduction to Apache Cassandra
 
Event sourcing with Eventuate
Event sourcing with EventuateEvent sourcing with Eventuate
Event sourcing with Eventuate
 
Walk-through: Amazon ECS
Walk-through: Amazon ECSWalk-through: Amazon ECS
Walk-through: Amazon ECS
 
Getting started with typescript and angular 2
Getting started with typescript  and angular 2Getting started with typescript  and angular 2
Getting started with typescript and angular 2
 
Introduction to Structured Streaming
Introduction to Structured StreamingIntroduction to Structured Streaming
Introduction to Structured Streaming
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
 
Petex 2016 Future Working Zone
Petex 2016 Future Working ZonePetex 2016 Future Working Zone
Petex 2016 Future Working Zone
 
How the web was won
How the web was wonHow the web was won
How the web was won
 
Drilling the Async Library
Drilling the Async LibraryDrilling the Async Library
Drilling the Async Library
 

Ähnlich wie HTML5, CSS, JavaScript Style guide and coding conventions

CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
Zohar Arad
 
Basics Of Css And Some Common Mistakes
Basics Of Css And Some Common MistakesBasics Of Css And Some Common Mistakes
Basics Of Css And Some Common Mistakes
sanjay2211
 

Ähnlich wie HTML5, CSS, JavaScript Style guide and coding conventions (20)

Web Design for Literary Theorists II: Overview of CSS (v 1.0)
Web Design for Literary Theorists II: Overview of CSS (v 1.0)Web Design for Literary Theorists II: Overview of CSS (v 1.0)
Web Design for Literary Theorists II: Overview of CSS (v 1.0)
 
Part 2 in depth guide on word-press coding standards for css &amp; js big
Part 2  in depth guide on word-press coding standards for css &amp; js bigPart 2  in depth guide on word-press coding standards for css &amp; js big
Part 2 in depth guide on word-press coding standards for css &amp; js big
 
4. Web Technology CSS Basics-1
4. Web Technology CSS Basics-14. Web Technology CSS Basics-1
4. Web Technology CSS Basics-1
 
Advanced Web Programming Chapter 8
Advanced Web Programming Chapter 8Advanced Web Programming Chapter 8
Advanced Web Programming Chapter 8
 
Introduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptxIntroduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptx
 
Introduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptxIntroduction to HTML+CSS+Javascript.pptx
Introduction to HTML+CSS+Javascript.pptx
 
CascadingStyleSheets in ONESHOT By DeathCodeYT .pdf
CascadingStyleSheets  in ONESHOT By DeathCodeYT .pdfCascadingStyleSheets  in ONESHOT By DeathCodeYT .pdf
CascadingStyleSheets in ONESHOT By DeathCodeYT .pdf
 
CSS Overview
CSS OverviewCSS Overview
CSS Overview
 
CSS Methodology
CSS MethodologyCSS Methodology
CSS Methodology
 
css-tutorial
css-tutorialcss-tutorial
css-tutorial
 
css-tutorial
css-tutorialcss-tutorial
css-tutorial
 
Cascading Style Sheets - Part 02
Cascading Style Sheets - Part 02Cascading Style Sheets - Part 02
Cascading Style Sheets - Part 02
 
Css.html
Css.htmlCss.html
Css.html
 
wd project.pptx
wd project.pptxwd project.pptx
wd project.pptx
 
Basics Of Css And Some Common Mistakes
Basics Of Css And Some Common MistakesBasics Of Css And Some Common Mistakes
Basics Of Css And Some Common Mistakes
 
DHTML
DHTMLDHTML
DHTML
 
WEB TECHNOLOGY Unit-2.pptx
WEB TECHNOLOGY Unit-2.pptxWEB TECHNOLOGY Unit-2.pptx
WEB TECHNOLOGY Unit-2.pptx
 
Html & CSS - Best practices 2-hour-workshop
Html & CSS - Best practices 2-hour-workshopHtml & CSS - Best practices 2-hour-workshop
Html & CSS - Best practices 2-hour-workshop
 
Introduction to Web Development.pptx
Introduction to Web Development.pptxIntroduction to Web Development.pptx
Introduction to Web Development.pptx
 
Introduction to Web Development.pptx
Introduction to Web Development.pptxIntroduction to Web Development.pptx
Introduction to Web Development.pptx
 

Mehr von Knoldus Inc.

Mehr von Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Kürzlich hochgeladen

CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
mohitmore19
 

Kürzlich hochgeladen (20)

Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
The Guide to Integrating Generative AI into Unified Continuous Testing Platfo...
 
Exploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdfExploring the Best Video Editing App.pdf
Exploring the Best Video Editing App.pdf
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verifiedSector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
Sector 18, Noida Call girls :8448380779 Model Escorts | 100% verified
 
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456LEVEL 5   - SESSION 1 2023 (1).pptx - PDF 123456
LEVEL 5 - SESSION 1 2023 (1).pptx - PDF 123456
 
Pharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodologyPharm-D Biostatistics and Research methodology
Pharm-D Biostatistics and Research methodology
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
Crypto Cloud Review - How To Earn Up To $500 Per DAY Of Bitcoin 100% On AutoP...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 

HTML5, CSS, JavaScript Style guide and coding conventions

  • 1. HTML5, CSS, JavaScript Style guide and coding conventions HTML5, CSS, JavaScript Style guide and coding conventions Priyanka Wadhwa Software Consultant Knoldus Software LLP Priyanka Wadhwa Software Consultant Knoldus Software LLP
  • 2. Agenda ● Why we need coding Standards? ● HTML5 coding conventions ● CSS style guide ● JavaScript Coding standards ● Why we need coding Standards? ● HTML5 coding conventions ● CSS style guide ● JavaScript Coding standards
  • 3. What is a need for coding standards ? Problem When 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 what’s 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…
  • 4.
  • 5. Need for coding standards Solution Coding 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.
  • 7. HTML5 coding conventions ● HTML5 doctype Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page. <!DOCTYPE html> <html> <head> </head> </html> ● Language Attribute A lang attribute is required to be specified on the root html element, giving the document's language. <html lang=”en-us”> <!→-→--> </html>
  • 8. ● Character encoding Ensure proper rendering of your content by declaring an explicit character encoding. <head> <meta charset=”UTF-8”> </head> ● Internet Explorer compatibility mode Internet Explorer supports the use of a document compatibility <meta> tag to specify what version of IE the page should be rendered as. <meta http-equiv=”X-UA-Compatibile” content=”IE=Edge”> ● CSS and JavaScript includes <link rel='stylesheet' href='guide.css'> <style>/* …… */</style> HTML5 Coding conventions
  • 9. ● Attribute order As 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-* <a class=”….” id=”…..” data-toggle=”model” href=”#”> Example link </a> <img src=”...” alt=”...”/> HTML5 Coding conventions
  • 10. ● Boolean attributes Requires no declaration. <input type=”text” disabled> <input type=”checkbox” value=”1” checked> <select> <option value=”1” selected>1</option> </select> ● Reducing markup Produce less HTML, avoid superfluous parent elements when writing HTML. <span class=”avatar”> <img src=”...”> </span> can be re-written as - <img class=”avatar” src=”...”> HTML5 Coding conventions
  • 11. 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
  • 13. CSS style guide Am I following the correct coding conventions here?
  • 14. CSS style guide Am I following the correct coding conventions here? And what about me?
  • 15. CSS style guide Am I following the correct coding conventions here? And what about me?
  • 16. 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.
  • 17. CSS style guide Syntax ● Use soft tabs with two spaces—they'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).
  • 18. 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"]. They’re only optional in some cases, and it’s a good practice for consistency. ● Avoid specifying units for zero values, e.g., margin: 0; instead of margin: 0px;.
  • 19. CSS style guide ● Declaration order Following 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.
  • 20. CSS style guide ● Don't use of @import From 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.
  • 21. 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.
  • 22. CSS style guide ● Single declarations Consider 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
  • 23. CSS style guide ● Shorthand notation Strive 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-radius Often 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.
  • 24. CSS style guide ● Comments Code 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.
  • 25. CSS style guide ● Class names Do 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-price Some good class names : .sequence { … }, .sequence-header { … }, .important { … } Not so good class names : .s { … }, .header { … }, .red { … }
  • 26. CSS style guide ● Selectors Keep 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).
  • 27. CSS style guide ● CSS quotations Use 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; }
  • 29. JS coding standards ● Variable Names Use of letters with camelCase in naming the variables. ✔ firstName = “Knoldus”; ✔ price = 9.90; ✗ middlename = “Softwares”; ● Spaces around operators Spaces should be used to differentiate operators and also after commas. ✔ var x = y + z; ✔ var values = [“knoldus” , “software”]; ✗ var values=[“knoldus”,“software”];
  • 30. JS coding standards ● Code Indentation 4 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 Rules Simple statements end with a semicolon. Like – declaring a variable var person = { firstName: “Knoldus”, lastName: “Softwares”, };
  • 31. 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.
  • 32. 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"};
  • 33. JS coding standards ● Line length < 80 characters If 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 Conventions Remember 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.
  • 34. JS coding standards ● Line length < 80 characters If 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 Conventions Remember 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?
  • 35. 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.
  • 36. 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

Hinweis der Redaktion

  1. specify a lang attribute on the root html element
  2. 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 pages 1 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
  3. For instance, if stylesheet A contains the text: @import url(&amp;quot;stylesheetB.css&amp;quot;); 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 &amp;lt;link&amp;gt; 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.