Standards for developing flexible, durable, and sustainable HTML and CSS.
Lovingly forked from @mdo
“Every line of code should appear to be written by a single person, no matter the number of contributors.”
</li>
or </body>
).Enforce standards mode and more consistent rendering in every browser possible with this simple doctype at the beginning of every HTML page.
From the HTML5 spec:
Authors are encouraged to specify a lang attribute on the root html element, giving the document's language. This aids speech synthesis tools to determine what pronunciations to use, translation tools to determine what rules to use, and so forth.
Read more about the lang
attribute in the spec.
Head to Sitepoint for a list of language codes.
Internet Explorer supports the use of a document compatibility <meta>
tag to specify what version of IE the page should be rendered as. Unless circumstances require otherwise, it's most useful to instruct IE to use the latest supported mode with edge mode.
For more information, read this awesome Stack Overflow article.
Quickly and easily ensure proper rendering of your content by declaring an explicit character encoding. When doing so, you may avoid using character entities in your HTML, provided their encoding matches that of the document (generally UTF-8).
Per HTML5 spec, typically there is no need to specify a type
when including CSS and JavaScript files as text/css
and text/javascript
are their respective defaults.
Strive to maintain HTML standards and semantics, but not at the expense of practicality. Use the least amount of markup with the fewest intricacies whenever possible.
HTML attributes should come in this particular order for easier reading of code.
class
id
, name
data-*
src
, for
, type
, href
title
, alt
aria-*
, role
Classes make for great reusable components, so they come first. Ids are more specific and should be used sparingly (e.g., for in-page bookmarks), so they come second.
A boolean attribute is one that needs no declared value. XHTML required you to declare a value, but HTML5 has no such requirement.
For further reading, consult the WhatWG section on boolean attributes:
The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.
If you must include the attribute's value, and you don't need to, follow this WhatWG guideline:
If the attribute is present, its value must either be the empty string or [...] the attribute's canonical name, with no leading or trailing whitespace.
In short, don't add a value.
Whenever possible, avoid superfluous parent elements when writing HTML. Many times this requires iteration and refactoring, but produces less HTML. Take the following example:
Writing markup in a JavaScript file makes the content harder to find, harder to edit, and less performant. Avoid it whenever possible.
"
).:
for each declaration.box-shadow
).rgb()
, rgba()
, hsl()
, hsla()
, or rect()
values. This helps differentiate multiple color values (comma, no space) from multiple property values (comma with space).0.5
instead of .5
and -0.5px
instead of -.5px
).#fff
. Lowercase letters are much easier to discern when scanning a document as they tend to have more unique shapes.#fff
instead of #ffffff
.input[type="text"]
. They’re only optional in some cases, and it’s a good practice for consistency.margin: 0;
instead of margin: 0px;
.Questions on the terms used here? See the syntax section of the Cascading Style Sheets article on Wikipedia.
[class^="..."]
) on commonly occuring components. Browser performance is known to be impacted by these.Additional reading:
Nesting is very helpful to define element states such as active and hover, pseudo elements like before and after, and minimal child selectors that don't justify an additional class name.
Variables in Sass are a powerful way to define values in one place that can be reused in multiple places in your project. They allow you to make changes from a central point without needing to use find and replace across multiple files and directories. [ref]
_user-settings.scss
.First, some basics:
This should be your first plan of attack. Using an @extend limits customizability but produces a more efficient CSS file. Smaller is better.
If you need to overwrite declarations of an @extend or need to pass values to it then you'll want to set up a mixin and use @include instead. Mixins are powerful and are generally used to accomplish complicated or labor-intensive tasks. Some examples:
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.
Be sure to write in complete sentences for larger comments and succinct phrases for general notes.
Place media queries inside their respective selector. Don't have entire blocks of code dedicated to a single media query.
Feel free to create a media query mixin to simplify modifying your queries.
Even in cases where you only have one rule per selector, avoid single-line formatting. In the same way that consistent trailing commas in Javascript makes for cleaner diffs, so does maintaining consistent formatting across all CSS rules, regardless of the number.
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.
The Mozilla Developer Network has a great article on shorthand properties for those unfamiliar with notation and behavior.
.btn
and .btn-danger
)..btn
is useful for button, but .s
doesn't mean anything..js-*
classes to denote behavior (as opposed to style), but keep these classes out of your CSS.Thanks to compilation and compression, we're able to organize styles into many small files without impacting the end user. Rules should be organized into small sets corresponding to the elements they style. Styles of unrelated elements should never be in the same file.
Consider the example on the right.
This rule obviously hides something, but it's not clear what it's hiding, or why. This code is unmaintainable, because its purpose is not obvious. Strive to write selectors and styles whose purpose and relationship is intuitive and obvious.
Recommended only. During the course of development this might not be realistic. Try to keep the following recommendations in mind.
Related property declarations should be grouped together following the order:
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.
Everything else takes place inside the component or without impacting the previous two sections, and thus they come last.
For a complete list of properties and their order, please see Recess.
Use spaces only, with 2 spaces per indentation level. Never mix tabs and spaces.
Try your best to limit all lines to a maximum of 80 characters. Do not ever go over 120.
Do not include trailing whitespace on any lines.
Use only unix-style newlines. \n
not \r\n
.
Use UTF-8 as the source file encoding.
Place 1 space before the leading brace.
Place 1 space before the opening parenthesis in control statements (if
, while
etc.). Place no space before the argument list in function calls and declarations.
Set off operators with spaces.
End files with a single newline character.
Leave a blank line after blocks and before the next statement.
Use a single blank line within the bodies of methods or functions in cases where this improves readability (e.g., for the purpose of delineating logical sections).
Do not use leading commas.
Use additional trailing commas.
This leads to cleaner git diffs. Also, transpilers like Babel will remove the additional trailing comma in the transpiled code which means you don't have to worry about the trailing comma problem in legacy browsers.
Always use explicit semicolons.
Use braces with all multi-line blocks.
If you're using multi-line blocks with if and else, put else on the same line as your if block's closing brace.
Use const
for all of your references; avoid using var
.
This ensures that you can't reassign your references (mutation), which can lead to bugs and difficult to comprehend code.
If you must mutate references, use let
instead of var
.
let
is block-scoped rather than function-scoped like var
.
Note that both let
and const
are block-scoped.
Use one const
/let
declaration per variable.
Group all your const
s and then group all your let
s.
This is helpful when later on you might need to assign a variable depending on one of the previous assigned variables.
Use ===
and !==
over ==
and !=
.
Conditional statements such as the if statement evaulate their expression using coercion with the ToBoolean
abstract method and always follow these simple rules:
true
false
false
+0
, -0
, or NaN
, otherwise true
''
, otherwise true
Use shortcuts when possible.
Strings:
Use parseInt
for Numbers and always with a radix for type casting.
Booleans:
Avoid single letter names. Be descriptive with your naming.
Use camelCase when naming objects, functions, and instances.
Use PascalCase when naming constructors or classes.
Use a leading underscore _
when naming private properties or methods.
Don't save references to this
. Use arrow functions or Function#bind
.
If your file exports a single class, your filename should be exactly the name of the class.
Use camelCase when you export-default a function. Your filename should be identical to your function's name.
Use /** ... */
for multi-line comments. Include a description, specify types and values for all parameters and return values.
Use //
for single line comments. Place single line comments on a newline above the subject of the comment. Put an empty line before the comment.
Prefixing your comments with FIXME
or TODO
helps other developers quickly understand if you're pointing out a problem that needs to be revisited, or if you're suggesting a solution to the problem that needs to be implemented. These are different than regular comments because they are actionable.
Use // FIXME:
to annotate problems.
Use // TODO:
to annotate solutions to problems.
Use object destructuring when accessing and using multiple properties of an object.
Use array destructuring.
Use object destructuring for multiple return values, not array destructuring.
You can add new properties over time or change the order of things without breaking call sites.
Always use modules (import
/export
) over a non-standard module system. You can always transpile to your preferred module system.
Do not use wildcard imports.
Import statements should be grouped in the following order:
Use single quotes ''
for strings.
When programmatically building up strings, use template strings instead of concatenation.
Template strings give you a readable, concise syntax with proper newlines and string interpolation features.
Use the literal syntax for array creation.
Use Array#push
instead of direct assignment to add items to an array.
Use array spreads ...
to copy arrays.
To convert an array-like object to an array, use Array#from
.
Use function declarations instead of function expressions.
Function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted. This rule makes it possible to always use Arrow Functions in place of function expressions.
Immediately-invoked function expressions:
Never declare a function in a non-function block (if
, while
, etc). Assign the function to a variable instead. Browsers will allow you to do it, but they all interpret it differently.
Never name a parameter arguments
. This will take precedence over the arguments
object that is given to every function scope.
Never use arguments
, opt to use rest syntax ...
instead.
Use default parameter syntax rather than mutating function arguments.
Use Object#assign
or jQuery#extend
to set default object values.
When you must use function expressions (as when passing an anonymous function), use arrow function notation.
It creates a version of the function that executes in the context of this
, which is usually what you want, and is a more concise syntax.
If you have a fairly complicated function, you might move that logic out into its own function declaration.
If the function body fits on one line and there is only a single argument, feel free to omit the braces and parentheses, and use the implicit return. Otherwise, add the parentheses, braces, and use a return statement.
Use the literal syntax for object creation.
Don't use reserved words as keys. It won't work in IE8. More info.
Use readable synonyms in place of reserved words.
Use computed property names when creating objects with dynamic property names.
They allow you to define all the properties of an object in one place.
Use object method shorthand.
Use property value shorthand.
Group your shorthand properties at the beginning of your object declaration.
Use dot notation when accessing properties.
Use subscript notation []
when accessing properties with a variable.
Always use class
. Avoid manipulating prototype
directly.
class
syntax is more concise and easier to reason about.
Use extends
for inheritance.
It is a built-in way to inherit prototype functionality without breaking instanceof
.
It's okay to write a custom toString()
method, just make sure it works successfully and causes no side effects.
Accessor functions for properties are not required.
If you do make accessor functions use getVal()
and setVal('hello')
.
If the property is a boolean, use isVal()
or hasVal()
.
It's okay to create get()
and set()
functions, but be consistent.
When attaching data payloads to events (whether DOM events or something more proprietary like Backbone events), pass a hash instead of a raw value. This allows a subsequent contributor to add more data to the event payload without finding and updating every handler for the event.
Prefix jQuery object variables with a $
.
Cache jQuery lookups.
Shopify is the only platform that we develop for that uses Liquid. Fortunately, they've done a great job on documentation and almost all of the info that you need can be found there.
The Objects link above is almost certainly the most important resource available to you when writing code for Shopify. It contains every single object you might come across during development and all of the values attached to them.
=
==
, !=
, <
, >
, etc.if
, unless
, and
, or
|
, minus:
, divided_by:
, strip
{{ }}
, {% %}
json
filterOutside of the WordPress environment, Pixel Union follows PSR-2 standards for PHP development. This is an overview of the higher-level rules for PSR-2, for the full set of standards please reference the PHP-FIG docs.
the PSR-2 Standard extends the PSR-1 Standard, documented here.
Note: The one way in which we diverge from PSR-2 is that we use 2 spaces for indents instead of 4. This is to maintain consistency between the other code styles, which are all 2 spaces.
use
declarations.abstract
and final
should be declared before the visibility; static
should be declared after the visibility.PascalCase
.camelCase
.namespace
declaration.use
declarations should go after the namespace
declaration.use
keyword per declaration.use
block.When making a method or function call:
Argument lists can be split across multiple lines, where each subsequent line is indented once. When doing so, the first item in the list should be on its own line, with only one argument per line.
The general style rules for control structures are as follows:
The body of each structure should be enclosed by braces. This standardizes how the structures look, and reduces the likelihood of introducing errors as new lines get added to the body.
function
keyword, and a space before and after the use
keyword.Like methods and functions, argument lists can be spread across multiple lines, using the same line-break and indentation style.
We have taken WordPress's PHP Coding Standards guide and placed it here. Fun.
Note:
Some parts of the WordPress code structure for PHP markup are inconsistent in their style. WordPress is working to gradually improve this by helping users maintain a consistent style so the code can become clean and easy to read at a glance.
Use single and double quotes when appropriate. If you’re not evaluating anything in the string, use single quotes. You should almost never have to escape quotes in a string, because you can just alternate your quoting style.
Text that goes into attributes should be run through esc_attr()
so that single or double quotes do not end the attribute value and invalidate the HTML and cause a security issue. See Data Validation in the Codex for further details.
Most theme-specific functions should be wrapped in a function_exists
test to allow child themes to override them. The function guard should use the alternative if endif
syntax.
Perl compatible regular expressions (PCRE, preg_
functions) should be used in preference to their POSIX counterparts. Never use the /e
switch, use preg_replace_callback
instead.
It’s most convenient to use single-quoted strings for regular expressions since, contrary to double-quoted strings, they have only two metasequences: \'
and \\
.
if
, elseif
, foreach
, for
, and switch
blocks.When formatting SQL statements you may break it into several lines and indent if it is sufficiently complex to warrant it. Most statements work well as one line though. Always capitalize the SQL parts of the statement like UPDATE
or WHERE
.
Functions that update the database should expect their parameters to lack SQL slash escaping when passed. Escaping should be done as close to the time of the query as possible, preferably by using $wpdb->prepare()
$wpdb->prepare()
is a method that handles escaping, quoting, and int-casting for SQL queries. It uses a subset of the sprintf()
style of formatting.
%s
is used for string placeholders and %d
is used for integer placeholders. Note that they are not ‘quoted’! $wpdb->prepare()
will take care of escaping and quoting for us. The benefit of this is that we don’t have to remember to manually use esc_sql()
, and also that it is easy to see at a glance whether something has been escaped or not, because it happens right when the query happens.
See Data Validation in the Codex for more information.
Avoid touching the database directly. If there is a defined function that can get the data you need, use it. Database abstraction (using functions instead of queries) helps keep your code forward-compatible and, in cases where results are cached in memory, it can be many times faster.
If you must touch the database, get in touch with some developers by posting a message to the wp-hackers mailing list. They may want to consider creating a function for the next WordPress version to cover the functionality you wanted.
Use lowercase letters in variable, action, and function names (never camelCase
). Separate words via underscores. Don’t abbreviate variable names un-necessarily; let the code be unambiguous and self-documenting.
Class file names should be based on the class name with class-
prepended and the underscores in the class name replaced with hyphens.
This file-naming standard is for all current and new files with classes. There is one exception for three files that contain code that got ported into BackPress: class.wp-dependencies.php, class.wp-scripts.php, class.wp-styles.php. Those files are prepended with class.
, a dot after the word class instead of a hyphen.
Files containing template tags in wp-includes
should have -template
appended to the end of the name so that they are obvious.
Prefer string values to just true
and false
when calling functions.
Since PHP doesn’t support named arguments, the values of the flags are meaningless, and each time we come across a function call like the examples above, we have to search for the function definition. The code can be made more readable by using descriptive string values, instead of booleans.
Ternary operators are fine, but always have them test if the statement is true, not false. Otherwise, it just gets confusing. (An exception would be using ! empty()
, as testing for false here is generally more intuitive.)
When doing logical comparisons, always put the variable on the right side, constants or literals on the left.
In the above example, if you omit an equals sign (admit it, it happens even to the most seasoned of us), you’ll get a parse error, because you can’t assign to a constant like true
. If the statement were the other way around ( $the_force = true )
, the assignment would be perfectly valid, returning 1
, causing the if statement to evaluate to true
, and you could be chasing that bug for a while.
A little bizarre, it is, to read. Get used to it, you will.
This applies to ==
, !=
, ===
, and !==
. Yoda conditions for <
, >
, <=
or >=
are significantly more difficult to read and are best avoided.
If using a module system (CommonJS Modules, AMD, etc.), require statements should be placed on separate lines at the top of the file.
These statements should be grouped in the following order:
Avoid extraneous whitespace in the following situations:
Additional recommendations::
=
+=
, -=
, etc.==
, <
, >
, <=
, >=
, unless
, etc.+
, -
, *
, /
, etc.If modifying code that is described by an existing comment, update the comment such that it accurately reflects the new code. (If possible, improve the code to be clear and concise, and delete the comment entirely.)
The first word of the comment should be capitalized, unless the first word is an identifier that begins with a lower-case letter.
If a comment is short, the period at the end can be omitted.
#
and a single space, and should be indented at the same level of the code that it describes.#
.#
and a single space.Use camelCase
(with a leading lowercase character) to name all variables, methods, and object properties.
Use UpperCamelCase
(with a leading uppercase character) to name all classes.
(The official CoffeeScript convention is camelCase, because this simplifies interoperability with JavaScript. For more on this decision, see [here][coffeescript-issue-425].)
Methods and variables that are intended to be "private" should begin with a leading underscore.
(These guidelines also apply to the methods of a class.)
.
""
) instead of single quoted (''
) stringsunless
over if
for negative conditions, especially for trailing conditionsunless...else
, use if...else
Annotation types:
TODO
: describe missing functionality that should be added at a later dateFIXME
: describe broken code that must be fixedOPTIMIZE
: describe code that is inefficient and may become a bottleneckHACK
: describe the use of a questionable (or ingenious) coding practiceREVIEW
: describe code that should be reviewed to confirm implementationIf a custom annotation is required, the annotation should be documented in the project's README.
@property
over this.property
@
return
where not required, unless the explicit return increases clarity...
) when working with functions that accept variable numbers of argumentsAt its most basic, source control gives us the ability to store, share, and transport code and code changes, but the real value comes from the ability to record and replay the stories behind each change during the lifetime of a project.
This is not an intro to source control or a git how-to: we assume that you have an intermediate understanding of how to use git. If you’re new to git, chapters 2, 3, and 6 (through the section on interactive rebasing) of Scott Chacon’s git book will tell you the how.
It doesn’t matter if you use git’s commands or a GUI (see GitHub for Mac and Gitbox), but you need a confident understanding of what’s happening regardless. Knowing the commands often helps.
To keep our many repositories easy to find we follow a simple naming convention:
Things to do right away:
Never commit directly to master. Instead, create small branches for each and every topic you work on (such as a feature or bug fix), and create a pull request into master when the branch is complete.
The exception to this rule is version commits and tags.
If your branch cannot be named as a specific function/feature/bug then you can create a long-running branch with a name like multiple_fixes
.
When using this method, it's important that the commits are clear and minimal (see Commits).
Please read Stephen Ball’s Steel City Ruby 2013 presentation, Deliberate Git. It covers this topic very well.
Once you’ve read it, you’ll understand why you should:
WIP
is fine.When writing commits:
If you’re pushing a new branch, use the --set-upstream
(-u
) flag to automatically set the remote branch as your local branch’s tracking branch.
So your pull request has been peer-reviewed and approved – nice work! Now it's time to merge your changes into master.
You want to use a fast-forward merge (git merge --ff-only
). Merging this way prevents "merge bubbles" where commit messages are created that say that a branch has been merged. This is called a recursive merge and it muddies up the commit history.
Versioned libraries, both internal and public, should follow these practices:
major_feature.minor_feature/major_bugfix.minor_bugfix
numbering schemev