My Coding Style and Guidelines

After Harry Roberts published his HTML/CSS coding style I’ve decided to follow his call and write down how I like to code and what my guidelines for HTML and CSS coding are.
This article is only a way to describe what I like to do – but it is by far not a recommendation or something. I have not really tried to “canalize” the coding style I do before but it is about time to do so and to write it down. Please let me know if you think that there are ways to do certain things better or in a more understandable way through comments.

Harry points out some over all pretty solid ways to keep the markup readable which I use too. The major one is whitespace, I think. To be true, I love whitespace. But I’ll come to this later.

General

Tabs or Spaces?

Personally I’ve learned to use tabs instead of spaces just a few weeks ago. Lea Verou lists up some arguments, why she thinks using tabs is the way to go. But there are still some use-cases for spaces she describes.
At /gebrüderheitz I’ve discussed using spaces with Steffen before. He works a lot with PHP and uses Tabs since… – ever! I have been using spaces because I ran into some difficulties with tabs in the past where code was totally wrong indented and stuff. But at the moment everything runs pretty smooth and I am happy with how it is.

Lettercase

HTML5 and CSS let you write code how ever you want to: UPPER-CASE, lower-case, CaMeL-cAsE. So this is all the same:

<section id="a-lovely-header" class="contains-a-logo">
<SECTION ID="A-LOVELY-HEADER" class="CONTAINS-A-LOGO">
<SeCtIoN iD="a-LoVeLy-HeAdEr" ClAsS="cOnTaInS-a-LoGo">

You have to make sure you use the according class in CSS and id in JavaScript, because they are both case-sensitive.

I use lower-case exclusively. I’ve never tried to use anything different as it does not seem natural to me. Apart for that, WHO THE HELL WANTS SO READ UPPER-CASE ALL THE TIME?! IS THE CODE REALLY YELLING AT YOU? HAVE YOU EVER SEEN THIS IN A SERIOUS BOOK? Ok – to be fair, I’ve never seen a serious book with all lower case. But camel-case? C’mon…
Camel-Case in JavaScript is totally perfect though.

HTML

Harry names a view key parts of HTML styling which I use and some I really do not like.

Unquoted Attributes

I never write unquoted attributes. Harry states that this is something he does, because he can. Well… That’s true. But as he points out he has some rules where he quotes attributes for example for generated content or content that changes a lot.

His opinion on using double-quotes for all the attributes is obvious, anyway:

It is more consistent on the whole, but by introducing rules I make my own consistency; if you can get away with not using quotes, then do so.

For me the rule “Don’t confuse others” applies here: When another programmer who is not familiar with writing attributes without quotes has to edit my code in a later stage of a project or just when checking the source of a project and sees this, she might be confused with what I wrote.
Apart for that, writing attributes without quotes is error-prone.

An example: You use the Media Object as described by Nicole Sullivan for your styles and need a button, you will probably add a class btn to your link. The action that this button takes care of is the primary target of a website. Thus you add another class primary-btn to the class-attribute. If you don’t use quotes, you’ll have to add them now. It may occur that you forget them. And now what?! You are screwed. This will lead into searching your template over and over again until you find this nasty little mistake you made earlier. I don’t want this! I like code that’s pretty much straightforward.

To be fair I have to say, that I use a build script for my code before it goes into production which minifies my HTML-code and thus removes unnecessary quotes. But this does not change my development coding style.

Self-Closing Tags

Omitting self-closing tags is a thing I really love about HTML (over XHTML). You can omit the closing tag. Actually I’ve seen people not using self-closing tags on images or inputs but using them in meta-tags. I don’t know what the sense behind this might be.
I just do not use them anywhere.

Optional Closing Tags

This is a thing people may get confused about, too. Just a view days ago someone re-filed the issue of missing closing tags for HTML5 Boilerplate’s 404-error-page template because he was confused of the missing stuff I guess. That’s why I try to always use the optional closing tags – again: don’t confuse anyone. At least I try to.

I remember Paul Irish had a great usage of optional closing tags for tables where you can align rows by using whitespace, so you can see the table’s layout in HTML. Not working with generated data, though.

Here’s the example

<table>
  <tr><th>Name           <th>Country       <th>Nonsense
  <tr><td>Rick Astley    <td>England       <td>Rickrolling
  <tr><td>Chuck Norris   <td>United States <td>Roundhouse-Kick
  <tr><td>Emeli Sandé    <td>Scotland      <td>Singin – Fo realz!
</table>

Whitespace

Oh yeah, whitespace. As I already pointed out I love whitespace in my code. Everything is a bit more obvious when you divide it into small parts. It gets easier to scan the code I think. Comments help with this too.
I like to divide bigger chunks of a page with a lot of whitespace. For example if you have a content-area and a sidebar, I try to keep them separate by using whitespace.
Apart from that grouping elements like definition-list-entries helps a lot with the readability of code.

I’ve made a gist with an example-file. Check it.

CSS

Using ids in CSS is something I try to avoid but it strikes me sometimes and I just do it if there are already ids defined on some elements. Mostly these are identifiers for header- or footer-sections. But I think it’s better use classes for styling concernes and ids for JavaScript and other stuff.

Anyway… The next part will not be about vanilla CSS. I use SASS (SCSS) nowadays and recently re-factored a corporate website for one of our customers at /gebrüderheitz in SASS. I want to share the way I worked with a lot of CSS in this case and did it sometimes before.

Structure

The website has a lot of styles which had to be refactored. These were organized in one big file that has about three thousand lines of code. I do not like to have a file that has so many code and is not clear by looking at it at first.
So I have decided to split up several parts into different files.

Before the refactoring we made an online style-guide, defining the elements that appear on the side. This style-guide will be used in other projects for the same customer, too and is essential for a corporate website. We tried to define as much as possible but also let designers have a free hand at what they do.

For all SASS-files I use a folder-structure which looks like this:

+ CSS
  + elements
  + helpers
  + modules
  + page
  styles.scss

The styles.scss file has a brief description of the project, who wrote the styles (copyright…) and includes (with @include) all other files which lie in the created folders.

+ helpers

helpers contains a file with pre-defined mixins, another file with all the variables for the project, a reset (in my case this is most of the HTML5 Boilerplate CSS, which contains Normalizer.css) and some other helper-classes which I use via mixins or with SASS’ @extend-method.

+ elements

In the element folder I include files with styles for styling native HTML elements. I’ve got a file named typography which contains definitions for the general copy-text, headlines, links, quotes aso. Another file contains all stylings that are connected to lists in the content (unordered-, ordered- and definition-lists). This folder also includes the styles for forms and tables.

+ modules

I mentioned the style-guide we defined for this project. This was a great help for me when dividing the CSS into parts because I was able to see which modules were needed for the page: boxes, a paginator, an accordion menu, the navigation and some other stuff.
For each module I have an own file which contains the styles of only one modules. So when I need to change something that has to do with the paginator, I’ll head over to the according file and change the desired values. This saves me a lot of searching and scrolling through a file. Apart from that, Sublime Text’s “Find in files” (cmd + Shift + F) feature lets you search trough all files in a project which is pretty handy. Text Mate has something similar I think. And if your editor does not support it, fire up the console and grep for the things you want to find.

+ page

This last folder contains all files that add a separate styling for any page or part of the website. Typical content might be the general layout and the header and footer styling for a page. Furthermore I define styles for an area of a website in this folder – e.g. if events need more styles than defined in the modules section, or a contact-form that has some extended stylings.

And More?

We have not yet done the styling for the mobile version of this website and thus the styles are not yet included into the project’s folder structure. Styles that are specific for devices with smaller width will go into a mobile-folder.
Another thing are stylesheets for print or other media. I’ve not yet found a proper way to include these. If you have any idea for this, let me know.

Whitespace & Comments

Back to the main CSS styling guidelines for my projects.

Typically I try to avoid too much rulesets in one file but sometimes you need to do this to not split one feature into several files, which is not the sense behind this modal.
Comments are a thing that help everyone reading the defined styles to unterstand them better. Most of the class names are pretty obvious and thus don’t require any further explanation. But if you define styles that are not obvious at the first glance or you need to use browser-hacks in any form it can be helpful for other programmers to include a short comment. At least I do it this way.
I try to think about “other programmers” as the programmer I might have become in three month, when I will look at the defined styles again. If I don’t know what I did three month ago, how is anyone else supposed to understand it. This needs to be avoided.

Formatting

One thing Harry mentions is that he does not use a lot of whitespace in his rulesets. I am allergic of this style of writing. I like to have really clean styles as this:

.some-rule {
  float: left;
  color: #666;
  text-decoration: underline;
}

For vendor prefixes he indents every rule so he can use typing in columns. As I use SASS I don’t really have to care about this. But I like the way he does it. I’ve done it the same way when I used to write vanilla CSS.

Indenting is somehow essential for the CSS nesting in SASS. For rules where the nesting does not work I don’t indent though.

And A Lot More

This is not everything that applies to my HTML and CSS workflow / guidelines. I hope I can write more about stuff like this in the future and share more of my thoughts. Feedback on my thoughts would be great.

Also: If you have some time, write down what your way of coding is. Share it on Twitter with the hashtag #codestyle.

27 Replies to “My Coding Style and Guidelines”

      1. I’ve looked into OOCSS as well, but I find SMACSS a lot better to handle, certainly when it comes to bigger project where more than one front-end developer is working on. With OOCSS, you’ll get lost pretty soon if no detailed agreement on naming conventions, documentation and so on is made upfront between developers (and everyone sticks to it). With SMACSS, everything is devided into modules. The base (grid, layout, typograph)can be setup pretty quickly, in a couple of hours or so, and the rest are only modules where everyone can work on.

        There are quite some thoughts on CSS development and ways to structure it, but SMACCS is my preferred way of working.

    1. Jitendra,

      as I use HTML5 Boilerplate in all of my projects, I got some IE-specific at hand which I use directly in my SASS-stylesheets.

      I don’t use any hacks anymore and I don’t like to target IE too much. I try to focus on feature-detection. The most CSS oddies can be bypassed by a) normalize.css and b) writing clean and efficient CSS.

      Everything else is handled with the classes mentioned before.

  1. Hi Hans,

    great Article.
    Very good to understand an much informative.

    My Question: How do you handle the page.css for many different pages on the website? On one page you don’t need some styles but on the other page you need this styles. Do you load all styles on every page?

    1. Alex, thanks for your feedback.

      Actually there is no page.css. There is a folder called page which contains some SCSS files. They are concatenated by SASS automatically and get minimized into one file. As the file is usally <70kB I don't split the CSS up and load it asynchronously or something. This is too much overhead for a really small benefit.

      Loading time is not an issue with a file that has around 70kB. I guess rendering time is more of a problem in the case that there are "slow" selectors or too many rules defined. But to be fair rendering-engines nowadays are really fast. I've no figues to prove that though.

    1. Dan –

      Having worked with lots of developers in my day, I have heard this phrase one too many times. Yes, theoretically, HTML and CSS are markup languages, not coding languages. However, with the recent surge of SASS and LESS extending CSS (and HAML with HTML), there has been a meshing of “coding” with “markup”. To use either SASS, LESS, or HAML, you have to have a good sense of using variables, math and expressions – which is the backbone of basic coding.

      Although I am not saying you are wrong, I do think there is a new argument emerging that, yes, using extensions of CSS and HTML are new ways of coding.

      If you don’t believe me, just go look at the LESS files for Bootstrap Twitter, or dive into the SASS/Compass of Sencha Touch 2. It may change your opinion on the term “coding” when it comes to front-end markup.

      – Wade

    2. Wikipedia (+ my comments):

      Computer programming (often shortened to programming or coding) is the process of designing, writing, testing, debugging, and maintaining the source code of computer programs.
      – you can design with css and html, write it, debug it in different browsers and maintain the source code

      This source code is written in one or more programming languages.
      – html & css…

      The purpose of programming is to create a set of instructions that computers use to perform specific operations or to exhibit desired behaviors.
      – instructions = html, css
      – desired operations/behaviors = render the page as you want it, do desired actions when clicking a link, play audio / video…

      The process of writing source code often requires expertise in many different subjects, including knowledge of the application domain, specialized algorithms and formal logic.
      – expertise in different subject: design (typography, colors, emotions…), devices (screen size, pixel density, touch, keyboard…), browsers (features, behaviors…)
      – application domain: different browsers and devices
      – specialized algorithms: browser hacks, cross browser compatibility…
      – formal logic: math for css 3d matrix, box-model, ems…

      (I omitted js + frameworks, less, sass…)

      Seems to me it has a lot in common with coding. ;)

    3. HTML and CSS development, when done right, involves using design patterns, clean coding standards and other conventions that ‘coders’ use. Setting up a modular front-end takes as much preparation and careful consideration as coding with any other language would.
      And in the end, what does it actually matter? As long as you create something that is usable, accessible, portable, scalable and something you can be proud of.

    4. That’s pretty much what I was going to post.

      But after reading about unquoted attributes, this whole thing is a joke and it doesn’t really matter.

  2. I have to agree withMax and Wade. I feel that the term coder/programmer should be accepted not only for the hardcore Perl/Haskel-Guys. But a lot of BackEnd-Engineer are offended when FrontEnd-Developer are calling themselves coders/programmers. Maybe it goes all back to the days when computer programms where only operating on the command line and didn’t look all that fancy. Or we have to find a term to distinguish “computer readable text” that related to visual stuff and “computer readable text” that takes a few seconds and in the end just spits out “some numbers”.

Leave a Reply

Your email address will not be published. Required fields are marked *