Little Book HTML Css Coding Guidelines
Little Book HTML Css Coding Guidelines
of HTML/CSS
Coding Guidelines
While the publisher and the author have used good faith efforts to ensure that the
information and instructions contained in this work are accurate, the publisher and
the author disclaim all responsibility for errors or omissions, including without limi‐
tation responsibility for damages resulting from the use of or reliance on this work.
Use of the information and instructions contained in this work is at your own risk. If
any code samples or other technology this work contains or describes is subject to
open source licenses or the intellectual property rights of others, it is your responsi‐
bility to ensure that your use thereof complies with such licenses and/or rights.
978-1-491-94257-4
[LSI]
For Michael Sage—
“Organization is not everything, but without organization, everything
is nothing.”
Table of Contents
Foreword. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix
vii
Foreword
Style guides and coding conventions might sound like something
creativity-encoraching—like painting inside the lines—but as a solo
developer, and especially when working in larger teams, style guide‐
lines tend to remove the least creative decisions and allow people to
focus on what matters—solving problems in code to make users’
lives better.
I met Jens at Google, and was an avid observer and sometimes col‐
laborator with his work on the webmaster team there—we were
both excited about trying to help codify and teach best practices for
web development. Jens and I both worked on and shared a desire to
build tools to help automate the decisions that we labored over and
it was fantastic to see how appreciative the teams were for insights
into the craft and for the ability of the tools Jens worked on to both
point out mistakes automatically or even correct them where possi‐
ble. As we both worked to decrease cognitive load, ditch double
break tags, and educate people about usability and accessibility,
more teams came to adopt coding guidelines to help speed up their
development, and stylistic nitpicking and confusion gradually rece‐
ded in the code review process.
Readability of code should be the goal of anyone in our field, much
as the AP Stylebook is a resource for some of the best news organiza‐
tions in the world. The rules can always be changed, but having a
sound and solid framework on which to build your next great idea
will make it that much easier to repurpose and share your efforts for
the betterment of users, and possibly other developers you may get
to work with. I’ve heard Dan Cederholm and Peter Paul Koch wax
poetic about the craft of web development—style guides and
improved readability are evidence of care for the craft.
Introduction
“It turns out that style matters in programming for the same reason that
it matters in writing. It makes for better reading.”
—Douglas Crockford
1 Throughout the book, I keep with the term coding guidelines, and use it liberally. I also
apply it holistically—that is, I use this term to denote serious sets of guidelines that try
to comprehensively define the formatting of all respective code, and not just represent a
weak recommendation to “please indent.” Normally, coding guidelines will apply to
non-minified, non-compressed working code. Live code (i.e., production code) consti‐
tutes an exception to most formatting guidelines.
1
are critical. Software and web development leave a lot of room for
preference, and preference makes for a lot of inconsistency and con‐
fusion, if not kept at bay.
As Wikipedia suggests, coding guidelines go beyond formatting;
they can also cover development principles, and with that direct
development with an even firmer grip.
In this Little Book, I share my experience with HTML and CSS cod‐
ing guidelines. Why me and why guidelines for HTML and CSS? A
web developer by trade, and one who’s closely following the devel‐
opment of web standards, I’m most familiar with HTML and CSS.
And I’m similarly familiar with coding guidelines. Ten years ago, I
introduced HTML/CSS rules at GMX, the largest email provider in
Germany. When I joined top agency Aperto, I did the same thing
and created, together with Timo Wirth, guidelines that ruled all
frontend code, including Aperto’s large commercial and governmen‐
tal customers. And later, I took the opportunity at Google to found a
team and with that team revise Google’s CSS guidelines and create
all new HTML guidelines.
The two most fundamental lessons I learned were that coding guide‐
lines absolutely are a cornerstone of professional web development,
and second (and in contrast to this), that it’s easier to set them up
than to get them followed. And this brings us into a good position to
start.
Acknowledgments
I’d like to thank Tony Ruscoe for his always friendly and professional
help checking and improving my technical writing. I thank the
O’Reilly team, notably Simon St. Laurent and Meg Foley, for their
advice and help on getting another Little Book out (following The
Little Book of HTML/CSS Frameworks). And, regarding the matter at
hand, I like to thank all the many people I’ve worked with who
showed and taught me how (not to) work with coding standards.
Thanks, too, go to Harry Roberts, Dan Hay, as well as Google’s and
WordPress’s developers for all their work on coding standards (and
permission to quote within this book).
.nav li,
.nav li a {
padding: 0 4px;
}
.nav li {
margin: 0 2px;
}
.nav li a {
margin: 0 -4px;
}
That is code from the same person: the author in 2002, and the
author in 2005.
What do we notice? The first thing we see is that the code is written
completely differently. It’s inconsistent. Would we want to work on
it? Probably not. Would we be able to work on it? Maybe.
What would change this? Focusing on high quality and an intelligi‐
ble, consistent formatting of all this code.
That is the job of coding guidelines.
Consistency
The major, direct benefit of coding guidelines is improved consis‐
tency. Why? Because with comprehensive coding guidelines all code
gets formatted the same way. Rules are always indented the same
way. Declarations appear in the same order. Element names are
always lowercase.
Consider this example:
#intro {
background: #fff;
color: #000;
}
.note {
color: gray;
background: white
}
Suppose you need to edit this style sheet. How do you specify and
order the colors for a new author section? Meet inconsistency.
While one might argue that keeping the guidelines in mind makes
the process of writing code itself a little slower, locating and refac‐
toring code becomes much easier and faster.
Usability
An indirect benefit that follows consistency is improved usability.
Improved developer usability, that is. Improved “ease of use and
learnability of code,” then, as I described in The Little Book of
HTML/CSS Frameworks. Why? Because through coding guidelines,
developers are able to set and trust expectations, which again helps
locating and refactoring code.
Maintainability
Lastly, coding guidelines and the consistency they bring to our code
help maintainability. They do so because guidelines constitute a
form of organization, a lower degree of entropy, which makes it eas‐
ier to order, or keep things in order. Although often forgotten,
maintainability important, as there’s no code in existence that will
only be touched once. Even if it’s not going to be edited or updated
again, eventually it must be decommissioned. And that falls under
maintenance, too.
Structure
At this point, we should work with a few examples. Let’s look at a
few random coding guidelines, without judgment nor endorsement:
.sub-content {}
Camel case and underscores are not used for regular classes; the
following are incorrect:
.pageHead {}
.sub_content {}
Dan Hay’s coding standards say the following about “verbose”
HTML code:
Don’t use tags that STADN (sit there and do nothing)
STADN tags do just that—they don’t actually contribute much to
the content or layout of a page. An example of a STADN tag would
be:
<FONT SIZE=2><B> </B></FONT>
The bold and font tags do not contribute to the layout or appear‐
ance of the non-breaking space. We could add as many surround‐
ing tags to the non-breaking space and it still wouldn’t affect the
appearance of the page.
Most HTML editors liberally insert STADN tags. This behavior is
yet another reason why HTML editors must not be used.
(A comment, “tag” should rather say “element” here.)
And for WordPress, vendor-specific extensions are worth special
attention:
We use grunt-autoprefixer as a pre-commit tool to easily manage
necessary browser prefixes, thus making the majority of this section
moot. For those interested in following that output without using
Grunt, vendor prefixes should go longest (-webkit-) to shortest
(unprefixed). All other spacing remains as per the rest of standards.
.sample-output {
-webkit-box-shadow: inset 0 0 1px 1px #eee;
-moz-box-shadow: inset 0 0 1px 1px #eee;
box-shadow: inset 0 0 1px 1px #eee;
}
(Legal note: This coding guideline has been quoted from the CSS
Coding Standards by WordPress, used under GPLv2.)
• What (not) to do
• Scope
• Examples
• Explanation
Minima
• What (not) to do
• Scope
• Example
• Detail: brief
Maxima
• What (not) to do
• Scope
• Examples
• Implementation help
• Explanation
• Detail: verbose
Prescriptive
If the reality/goal difference is bigger, we want to take a prescriptive
(i.e., normative) approach, meaning to tell what to do:
Release only valid HTML code
Mixed
Yet then, in everyday coding life, we face coding practices we want
to document (describe), and others we want to achieve (prescribe).
This means that most coding guidelines and standards include rules
that are mixed, using both approaches.
Decision Process
How do we decide when to use which coding guidelines? The flow‐
chart in Figure 1 can help us:
What we can see is that for a team of one, we don’t strictly need
coding guidelines. It is recommended, however, to look into using
coding guidelines even in this case—perhaps making use of public
ones, such as the Google HTML/CSS Style Guide with the exception
of two-space indentation (even after leaving Google, I still follow
these guidelines for my personal projects).
Whenever two or more people work together, however, coding
guidelines become useful, and really important. And there the ques‐
tion is one of goals, and existing quality, to say whether we need a
descriptive or prescriptive approach, considered for each guideline.
Compliance
The next important aspect is achieving compliance—that is, enforc‐
ing the guidelines. This is normally a two-fold process.
First, we need to measure whether coding guidelines are followed or
not. For that, we need to set up the necessary infrastructure and
tools, though manually probing for compliance, as with code
reviews, does work, too. In practice, this piece is neglected rather
frequently, and organizations don’t know much about their actual
compliance rates. Automation, which we will look at momentarily, is
crucial here. How to automate the whole compliance part is not sub‐
ject of this booklet, however.
Second, we need to enforce the code style we want to see. Here,
too, automation is desirable, but we also need a way to track and
score offenders. Tying coding style compliance to performance met‐
rics that got communicated in advance is an effective approach. For
example, a team member who repeatedly violates coding standards
could get a lower performance rating than one who does keep
with it.
Reviews
Our coding guidelines should not be considered a one-off effort.
Just as we must maintain our code, so too should our guidelines be
reviewed from time to time—it’s important to update the documen‐
tation to reflect changes to guidelines as they arise.
It is something that gets maintained (as much as the affected code—
we should not forget to update it when guidelines change). It is
therefore recommended to not only assign a primary contact (or
perhaps a small team of experienced volunteers) to be guideline
Automation
Lastly, a particularly useful habit—and a key for future handling of
coding guidelines—is automation. The assessment of code quality
should be automated as much as possible and we should also auto‐
mate improving and fixing code.
At the moment, there is no single out-of-the-box solution for this
(only small scripts abound), but our vision overall should be that
our development environment shows us local coding preferences,
highlights violations and fixes them for us; that then, when we stage
our code, additional checks are run that likewise report issues and
fix them, and that at the end, optimized, minified, compressed, our
code goes live in the shape we had envisioned it.
General
Use UTF-8 (No Byte Order Mark)
Make sure your editor uses UTF-8 as character encoding, without a
byte order mark.
HTML
Use HTML 5
Use HTML 5 (HTML syntax) for all HTML documents: <!DOCTYPE
html>.(this spelling is for historical reasons).
Although technically correct, do not close void elements—write
<br>, not <br />.
Use a New Line for Every Block, List, or Table Element, and Indent Every
Such Child Element
Independent of the styling of an element (as CSS allows elements to
assume a different role per display property), put every block, list, or
table element on a new line.
Also, indent them if they are child elements of a block, list, or table
element.
(If you run into issues around whitespace between list items, it’s
acceptable to put all li elements in one line. A linter is encouraged
to throw a warning instead of an error.)
Correct:
<table>
<thead>
<tr>
<th scope="col">Income
<th scope="col">Taxes
<tbody>
<tr>
<td>$ 5.00
<td>$ 4.50
</table>
CSS
Use Valid CSS Where Possible
Unless dealing with CSS validator bugs or requiring proprietary syn‐
tax, use valid CSS code.
Use tools such as the W3C CSS validator to test.
Using valid CSS is a baseline quality attribute that allows us to spot
CSS code that may not have any effect and can be removed, and
ensures proper CSS usage.
/* Presentational */
.button-green {}
.clear {}
Correct:
/* Specific */
#login {}
.video {}
/* Generic */
.aux {}
.alt {}
Use ID and Class Names that Are as Short as Possible but as Long as
Necessary
Try to convey what an ID or class is about while being as brief as
possible.
Using ID and class names this way contributes to acceptable levels of
understandability and code efficiency.
Incorrect:
#navigation {}
.atr {}
Correct:
#nav {}
.author {}
Alphabetize Declarations
Put declarations in alphabetical order in order to achieve consistent
code in a way that is easy to remember and maintain.
Ignore vendor-specific prefixes for sorting purposes. However, mul‐
tiple vendor-specific prefixes for a certain CSS property should be
kept sorted as well (e.g., -moz prefix comes before -webkit).
(Exceptions prove the rule, so in the event of the cascade pushing
order on us, that’s fine.)
Correct:
background: fuchsia;
border: 1px solid;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
border-radius: 4px;
color: black;
text-align: center;
text-indent: 2em;
html {
background: #fff;
color: #444;
}
Use a Space Between the Last Selector and the Declaration Block
Always use a single space between the last selector and the opening
brace that begins the declaration block. The opening brace should
be on the same line as the last selector in a given rule.
Incorrect:
#video{
margin-top: 1em;
}
#video
{
margin-top: 1em;
}
body {
margin: auto;
width: 50%;
}
Use Single Quotation Marks for Attribute Selectors and Property Values
Use single ('') rather than double ("") quotation marks for attribute
selectors or property values. Do not use quotation marks in URI val‐
ues (url()).
Exception: If you do need to use the @charset rule, use double quo‐
tation marks, as single quotation marks are not permitted.
Correct:
@import url(//example.com/default.css);
html {
font-family: 'helvetica neue', helvetica, sans-serif;
}
Colophon
The cover image is by 掬茶 (Own work) [CC BY-SA 3.0 (http://crea‐
tivecommons.org/licenses/by-sa/3.0)], via Wikimedia Commons.