-
1.1 Always use const or let
-
Use const by default.
-
Use let when a variable needs to be reassigned.
-
Avoid using var
-
1.2 One variable per declaration, semicolons are required.
// Bad code
const a = 1, b = 2, c = 3; const $header = $('.header'), $footer = $('.footer'), $main = $('.main'); let car = {}, pet = {};
// Good code
const a = 1;
const b = 2;
const c = 3;
const $header = $('.header');
const $footer = $('.footer');
const $main = $('.main');
let car = {};
let pet = {};
- 1.3 Group all your
const
s and then group all yourlet
s.
// Bad
let a;
const const1 = 'const1';
let b;
const const2 = 'const2';
let c;
// Good
const const1 = 'const1';
const const2 = 'const2';
let a;
let b;
let c;
- 1.4 Assign variables where you need them
// bad - unnecessary function call
function checkName(hasName) {
const name = getName();
if (hasName === 'test') {
return false;
}
if (name === 'test') {
this.setName('');
return false;
}
return name;
}
// good
function checkName(hasName) {
if (hasName === 'test') {
return false;
}
const name = getName();
if (name === 'test') {
this.setName('');
return false;
}
return name;
}
- jQuery object must be cached and have prefix `$`.
// Bad
const sidebar = $('.sidebar');
$('.popup').show();
...
$('.popup').show();
// Good
const $sidebar = $('.sidebar');
const $popup = $('.popup');
$popup.hide();
...
$popup.show();
- Use single quotes, not double quotes.
// Bad
let directive = "No identification of self or mission.";
let saying = 'Say it ain\u0027t so.';
// Good
let directive = 'No identification of self or mission.';
let saying = `Say it ain't so`;
- Use template strings instead of concatenation.
// Bad
function sayHi(name) {
return 'Hi ' + name + ' , how are you ?';
}
// Good
function sayHi(name) {
return `Hi ${name}, how are you ?`;
}
- Meaningful names, prefer camelCase, avoid underscores.
// Bade
const a = 20;
const nErr = 'number error';
this.__firstName__ = 'Panda';
this.firstName_ = 'Panda';
this._firstName = 'Panda';
// Good
const age = 20;
const numErrors = 'number error';
this.firstName = 'Panda';
- Use ALL_UPPERCASE when naming constant variables.
// Bad
const pi = 3.1416;
const logo_name = 'Sunbytes';
// Good
const PI = 3.1416;
const LOG_NAME = 'Sunbytes';
- Use camelCase when naming objects, functions, and instances.
// Bad
const NEWObject = {};
const my_function = () => {};
const NewPerson = new PerSon();
// Good
const newObject = {};
const myFunction = () => {};
const newPerson = new Person();
- Use PascalCase only when naming constructors or classes.
// Bad
function pet(options) {
this.name = options.name;
}
const kiki = new pet({
name: 'Ki Ki',
});
// Good
class Pet {
constructor(options) {
this.name = options.name;
}
}
const kiki = new Pet({
name: 'Ki Ki',
});
- Don't save references to `this`. Use arrow functions or Function bind.
// Bad
function showPlace() {
const that = this;
return function () {
console.log(that);
}
}
// Good
function showPlace() {
return () => {
console.log(this);
}
}
Bad code
const y=x+5;
function getContent(){
...
}
function getContent( options ) {
...
}
$button.on('click',{
...
})
Good code
const y = x + 5;
function getContent() {
...
}
function getContent(options) {
...
}
$button.on('click', {
...
})
Bad code
import { es6 } from './javascript';
...
export es6;
Good code
import { es6 } from './javascript';
...
export es6;↵
- End json properties with a single comma
Bad code
const object = {
name: 'Bob',
age: 20
}
Good code
const object = {
name: 'Bob',
age: 20,
}
-
To minimise conflict potential all
-
Example: Wordpress plugin WooCommerce use classes `.woocommerce-`
-
Use a more traditional BEM approach to naming classes.
-
Document: http://getbem.com
-
**Block**: being independent allows for their re-use\
-
**Element**: A constituent part of a block that can not be used outside of it.\
-
**Modifier**: Flags on blocks or elements. Use them to change appearance or behaviour.
-
Example:
-
modifier: `.woocommerce-loop-product_sale`\
-
element: `.woocommerce-loop-product__link`\
-
element: `.woocommerce-loop-product__title`\
-
element: `.woocommerce-loop-product__price`\
-
element: `.woocommerce-loop-product__rating`\
-
element: `.woocommerce-loop-product__button-add-to-cart`\
-
modifier: `.woocommerce-loop-product__button-add-to-cart_added`
Bad code
datasetlist,
dataset_list,
datasetList
good code
dataset-list
-
Choose semantic names.
-
Choosing great variable names.
-
Avoid the `*` wildcard selector.
-
Do not use external link (google font, css of framework, ...).
-
Use display: flex instead of float and display: inline-block.
-
Avoid extra selectors.
Bad code:
body #container .someclass ul li {....}
Good code:
.someclass li {...}
- Use only lowercase.
Bad code:
color: #ACEFD1;
display: BLOCK;
<DIV></DIV>
Good code:
color: #acefd1;
display: block;
<div></div>
- Always end in a semicolon.
Bad code:
color: #fff
Good code:
color: #fff;
- Make it `readable`: easier to re-use, maintain and develop in the future
Bad code
.example{background:red;padding:2em;border:1px solid black;}
Good code
.example {
background: red;
padding: 2em;
border: 1px solid black;
}
- Do not put “0”s in front of values or lengths between -1 and 1.
Bad code:
font-size: 0.8em;
Good code:
font-size: .8em;
- Avoid units on zero values.
Bad code:
margin: 0px 0px 2px 0px;
Good code:
margin: 0 0 20px 0;
- Avoid using tag names with ID or class name.
Bad code:
ul.example {}
p#container {}
Good code:
.example {}
#container {}
- Avoid use IDs in selectors.
Bad code:
btn#download
Good code:
.download
-
Avoid duplicate properties.
-
Caps lock for meaning, text-transform for style `text-transform: uppercase`.
-
Use absolute `position` only when you have to, `no choice`.
- Always specify a fallback generic font.
Bad code:
font-family: "Helvetica Neue";
Good code:
font-family: "Helvetica Neue", Tahoma, sans-serif;
\
- Font names with spaces must surrounded by double-quotes.
Bad code:
font-family: Helvetica Neue, Tahoma, sans-serif;
Good code:
font-family: "Helvetica Neue", Tahoma, sans-serif;
\
- Font weights should be defined using numeric values.
Bad code:
font-weight: bold;
Good code:
font-weight: 700;
- All color values are written in the hexadecimal format and using lowercase.
Bad code:
color: #ACEFD1;
color: white;
Good code:
color: #acefd1;
color: #fff;
- Use 3 character hexadecimal notation where possible.
Bad code:
color: #eebbcc;
color: #ffffff;
Good code:
color: #ebc;
color: #fff;
- If you need transparency, use rgba.
Good code:
color: rgba(0, 0, 0, .6);
bacground: rgba(0, 0, 0, .6);
- Use shorthand properties where possible
Bad code:
img {
margin-top: 5px;
margin-right: 10px;
margin-bottom: 5px;
margin-left: 10px;
}
button {
padding: 0 0 0 20px;
}
Good code:
img {
margin: 5px 10px;
}
button {
padding-left: 20px;
}
-
Place @extends and @includes at the top of your declaration list.
-
Place concatenate selectors second.
-
Place pseudo states and elements third.
-
Place nested selectors last.
-
Place pseudo-class/ nested selectors after an empty line.
Good code:
.element {
@extend .other-element;
background: #000;
&:hover {
background: #333;
}
}
-
Use pixel (px) unit – corresponds to actual pixels on the screen – for margin, padding
-
Use rem (rem) unit – corresponds to the specified point size of the font – for text
-
Use percentage (%) unit for full width content
-
Use unitless values when you can. Favor rem if you use relative units. Prefer seconds over milliseconds.
Bad code:
div {
margin: 0px;
font-size: .9em;
line-height: 22px;
transition: 500ms;
}
Good code:
div {
margin: 0;
font-size: 1rem;
line-height: 1.5;
transition: .5s;
}
Bad code:
h1 {
font-family: verdana;
color: #e1e1e1;
}
h2 {
font-family: verdana;
color: #e1e1e1;
}
Good code:
h1,
h2 {
font-family: verdana;
color: #e1e1e1;
}
Use caniuse or a similar service to check if what you are using is widely supported, if it needs prefixes, or if it causes any bugs in a certain platform. (https://caniuse.com/)
Bad code:
.ball {
left: 50px;
transition: 0.4s ease-out;
}
.ball.slide-out {
left: 500px;
}
Good code:
.ball {
left: 50px;
transition: left 0.4s ease-out;
}
.ball.slide-out {
transform: translateX(450px);
}
https://www.html5rocks.com/en/tutorials/speed/high-performance-animations/
Bad code:
li {
visibility: hidden;
}
li:first-child {
visibility: visible;
}
Good code:
li + li {
visibility: hidden;
}
- Do not duplicate style declarations that can be inherited.
Bad code:
div h1,
div p {
text-shadow: 0 1px 0 #fff;
}
Good code:
div {
text-shadow: 0 1px 0 #fff;
}
- Prefer English over math
Bad code:
:nth-child(2n + 1) {
transform: rotate(360deg);
}
Good code:
:nth-child(odd) {
transform: rotate(360deg);
}
Bad code:
.news {
background: #eee;
border: 1px solid #ccc;
border-radius: 6px;
}
.events {
background: #eee;
border: 1px solid #ccc;
border-radius: 6px;
}
Good code:
.feat-box {
background: #eee;
border: 1px solid #ccc;
border-radius: 6px;
}
-
One of the best practices for writing CSS is placing a comment on each group of elements.
-
Comments should be used liberally to explain anything that may be unclear at first glance, especially IE workarounds or hacks.
-
Explain code as needed where possible.
-
List of elements are inline: span, a, strong, em, img, br, input, abbr, acronym
-
List of elements are block: div, h1 … h6, p, ul, li, table, blockquote, pre, form
-
Avoid using as little browser-specific hacks if at all possible.
-
Avoid user agent detection as well as CSS “hack” -- try a different approach first.
https://jigsaw.w3.org/css-validator/
-
When you break your styles into smaller and more focused stylesheets it’s easier to document them.
-
You can also save time by not having to document what becomes self-explanatory.
header.scss
button.scss
main.scss
form.scss
-
Some simple comments are all it takes to organize a style sheet and make it more accessible to your colleagues or your future self.
-
Style guide can help you determine a good structure for your CSS because to create one you will need to distinguish between:
-
the baseline styles that define the look and feel of your application.
-
the customizations that are done to specific components.
-
the customizations that are done to specific pages.
Bad code:
.message-error {
border: 1px solid red;
color: red;
background: #fff;
font-weight: bold;
}
.message-ok {
border: 1px solid green;
color: green;
background: #fff;
font-weight: bold;
}
.message-warn {
border: 1px solid orange;
color: orange;
background: #fff;
font-weight: bold;
}
Good code:
.message-error,
.message-ok,
.message-warn {
border: 1px solid;
font-weight: bold;
background: #fff;
}
.message-error {
border-color: red;
color: red;
}
.message-ok {
border-color: green;
color: green;
}
.message-warn {
border-color: orange;
color: orange;
}