HTML/CSS: An overview of effective coding standards.

Luqman Ahmed
11 min readJul 18, 2019

--

When you start sharing code, or start reading code-shared by others, you begin to realize that not everybody writes their code they way you do. You see that other, ugly coding style, and think “everybody needs to write in the same style so that things are easier for me to understand.” Thus, it is natural that everybody wants their own habits turned into the standard, so they don’t have to change their habits

###########################################

“Every line of code should appear to be written by a single person, no matter the number of contributors.”

###########################################

Code speaks for you. Regardless of whether you are a novice or an expert, if the code is messy, it leaves a poor impression. A lot of coding best practices emphasize keeping code lean and well organized. The general practices within HTML/CSS/JS or any other language are no different. The goal is to write well-structured and standards-compliant markup.

No one will blame you if you use four spaces instead of tab. However, as a good developer, you must make your masterpiece neat and clean. After all, code is poetry.

Lets take a look at this piece of code:

Then compare it to this:

Indenting is not the only issue in the above example. If you look closely you'll see that the anchors were missing title attribute also the first alphabet of the links is uppercase. Writing clean code makes the code easier to understand going forward and is essential for creating a successful maintainable product. The element’s attributes also play an important role when it comes to SEO.

Principles of Standardized Code

There are several guiding principles with Code Standards. These represent the core concepts of standardized code.

  • Code should be readable and understandable by all members of the team. This includes internal and external developers.
  • All code, regardless of the project, should read as if it was developed by a single person regardless of how many individuals actually worked on it.
  • The style of writing and implementation of these Code Standards is agreed upon and implemented by the team.
  • Assist in developing well-formed, semantically correct, and mostly valid code.
  • Aid in the onboarding of new development team members to new and existing projects.

Code Re-usability:

Code which shares a very similar or identical structure should be written in such a way that it can be used further. The aim of code reusability is to provide a common structure so that developers don’t have to redo it from scratch and can reuse the code provided. In this way, code reusability allows us to cut out much of the work and save a lot of time.

Code Check:

Before submitting the code it should be reviewed and checked properly maintaining the above guidelines rules. It will help understand the third party user easily without facing any difficulties.

Readability and Minification

When developing, readability is preferred over compression. There is no need for a developer to purposefully (manually or automatically) compress HTML or CSS/JS.

############################################

HTML

HTML acts as the Structure or skeleton for which our Presentation (Styles) and Functionality (JavaScript) are built on. This makes it the foundation of the other components of our Front-End. Its semantics can have an either a positive, or negative, impact on:

  • Browser Rendering Speed
  • Search Engine Optimization (SEO)
  • Accessibility
  • Validation
  • Usability

Semantics

HTML5 provides us with lots of semantic elements aimed to describe precisely the content — take advantage of its rich vocabulary. Make sure you understand the semantics of the elements you’re using.

NOTE: It’s worse to use a semantic element in the wrong way than staying neutral.

Good developers can write valid HTML markup that is formatted properly and easy to read. Great developers go beyond that and know when to use the appropriate element for the job.

Divitis/Classitis

Divitis/Classitis refers to the over-use of the div tag and css classes for purposes other than dividing a page into meaningful sections. These include:

  • wrapping elements in a div in order to insert class and/or id attributes for styling with CSS
  • manipulating page structure to accomplish specific visual goals
  • using a div tag to mark-up items that don’t seem to match any other HTML element

The end result is a document full of nested div tags reflecting the old method of nesting tables. HTML is a structural mark-up language. It is meant to provide semantic (meaningful) structure to documents in the form of headers, lists, paragraphs, images, metadata, and other elements. It is not meant to be used for visual presentation. That is what CSS is for. This means that you should try to limit your HTML to the minimum elements necessary to define the structure of your document.

You can also apply multiple classes to a single div instead of using an extra div to apply a second class.

Instead of this:

Do this:

Formatting

All CSS documents must use two spaces for indentation and files should have no trailing whitespace. Other formatting rules:

  • Use soft-tabs with a two space indent.
  • Use double quotes.
  • Use shorthand notation where possible.
  • Put spaces after : in property declarations.
  • Put spaces before { in rule declarations.
  • Use hex color codes #000 unless using rgba().
  • Always provide fallback properties for older browsers.
  • Use one line per property declaration.
  • Always follow a rule with one line of whitespace.
  • Always quote url() and @import() contents.
  • Do not indent blocks.

Attribute Order

HTML attributes should come in this particular order for easier reading of code.

  • src, for, type, href, value
  • class
  • id, name
  • title, alt
  • role, aria-*
  • data-*

As far as Identifiable information is concerned, Class`s make for great reusable components, so they come first. IDs are more specific and should be used uniquely.

Boolean Attributes

XHTML required you to declare a value for all attributes, but HTML5 has no such requirement for boolean attributes. A list of some of these boolean attributes includes:

  • autofocus
  • selected
  • checked
  • disabled
  • readonly
  • multiple
  • required
  • novalidate
  • formnovalidate
<input type="text" disabled>
<input type="checkbox" value="1" checked>
<select>
<option value="1" selected>1</option>
</select>

The W3C Spec for Boolean Attributes has additional information on these boolean attributes.

Images

An image that has informational value should be a part of the markup and include an appropriate alt attribute.

If an image is purely decorative (it provides no content value other than visual flair to the page) then a background-image is appropriate. An inline image can also be used, but with the appropriate ARIA and role attributes applied.

<img src="../path/to/image/file.jpg" alt="" aria-hidden="true" role="presentation"

These attributes should also be applied when defining an inline SVG icon that is used for presentational purposes only.

Block Element Modifier (BEM)

Block Element Modifier (BEM) is a highly useful, powerful, and simple naming convention that makes your front-end code easier to read and understand, scale, robust and explicit, and a lot more strict.

The BEM approach ensures that everyone who participates in the development of a website works with a single codebase and speaks the same language — exactly what we’re looking for! Using BEM’s proper naming convention will better prepare you for design changes made to your website.

The naming convention follows this pattern:

BEM style simple naming convention
  • .block represents the higher level of an abstraction or component.
  • .block__element represents a descendant of .block that helps form .block as a whole.
  • .block--modifier represents a different state or version of .block
An analogy/model for how elements are related:

Think CSS in objects

To write modular CSS you have to push yourself to think in objects. What are the objects in this case? Objects are small independent parts of functionality. UI elements like headers, footers, buttons or form elements are objects.

Objects are always declared using a class selector. ID and tag based selectors are not that easy to customize. For example to override an ID based selector you have to declare a selector chain with 255 classes to override one ID.

The & selector in SASS makes it easy to define different "states" of an object. In the above example we define the "hover" state for the button.

Parent-child relationship

Using a consistent naming scheme to define the parent-child relationship between objects helps to write much cleaner CSS code. Here’s an example:

As you can see in the above example we came up a hard relationship parent element .post and the child element .title. The styling of the title will only be applied when the parent element has the class .post. That means we don't have the chance to use the post title in a modified version for another object. So let's try to get rid of the hard relationship between these two selectors:

The main benefit of this approach is that the defined styles can be used throughout the application & we don’t have to worry about conflicts with similar named objects.

Subclassing objects

The most object-oriented concepts are using the concept of extending classes from other objects. This technique is called “subclassing”. This is useful when you want to extend the properties of the object & define additional properties.

Let’s go back to the button example and extend it to a drop down button:

In this example we extended the button and transformed it to a drop down button. To use those button styles we have to apply both classes to the “button” element:

Using modifiers

A modifier can be used to define a certain state for an element or apply modifications to the behavior and / or styling.

For states we’re using the prefix is--.

Another example would be to modifying the behavior of the element. In the following example we can modify the size of a form element using modifiers:

In the above example, we defined the modifiers only for this specific object. That’s why we’re using & parent selector.

Selector depth

SASS provides us with the ability to nest our rules which is a great feature but can be dangerous when you have to make sure your styles can easily be customized by the user. As a general rule a maximum of 3 nesting layers is perfect. It provides us with enough room to use nesting throughout our styling and doesn’t produce overly complicated selectors.

Let’s take a look on a bad usage of nesting:

Over nesting and results

As you can see the processed result provides us with selectors which nobody would like to override to provide custom styling. To match our guidelines we’re splitting the object in two objects and using subclassing:

Splitting the object in two objects and using subclassing

Keep Your Sass Rules in Order

It is important to keep consistency in the code. One of the rules is that you need to keep the order of rules. This way other developers can read the code with much more understanding and will spend less time finding their way around. Here is the proposed order:

  1. Use @extend first. This let you know at first that this class inherits rules from elsewhere.
  2. Use @include next. Having your mixins and functions included at top is nice to have, and also allows you to know what you will be overwriting (if needed).
  3. Now you can write your regular CSS class or element rules.
  4. Place nested pseudo classes and pseudo elements before any other element.
  5. Finally, write other nested selectors like in the following example:

tl;dr — Round up

Objects will be named with a noun:

.noun {}            // examples: .button, .menu, .textbox, .header

Parent-child relationships will be named a noun too:

.noun {}            // parent:  .post
.noun-noun {} // child: .post-title

Subclasses using a prefixed adjective which defines the type:

.adjective--noun {} // examples: .dropdown--button, .tooltip--button

Modifiers are using state classes:

.is--state {}       // state: .is--active, .is--hidden

Classes, which will be applied to an element using JavaScript using the prefix js--:

.js--noun {}        // examples: .js--slider, .js--modal

Support classes using the prefix has-- and defining the feature:

.has--property {}   // examples: .has--boxshadow, .has--localstorage

Optimizing for performance

Site speed can make or break conversion rates and impact your site’s revenue, so keep your page load time low by writing code semantically, use best practices and routinely cleaning up your CSS, HTML and images.

Having a light CSS file is essential in optimizing a web page loading speed. No matter how experienced you are as a developer, there’s a good chance that your website contains CSS that have no impact on current page elements. For example, frameworks like Bootstrap come with dozens of CSS styles that you probably don’t need. Unused CSS just adds dead weight to your applications and contributes to the growth of web page size, so you want to make sure that you have as little excess code as possible.

Eliminating Unused CSS Manually

If you’re using Chrome, the DevTools tab has a handy tool that allows you to see what code is being executed on a page on what isn’t. To access this tool, follow the steps below:

  1. Open Chrome DevTools
  2. Open the command menu with: cmd + shift + p
  3. Type in “Coverage” and click on the “Show Coverage” option
  4. Select a CSS file from the Coverage tab which will open the file up in the Sources tab

Any CSS that is next to a solid green line means that the code was executed. Solid red means it did not execute. A line of code that is both red and green, means that only some code on that line executed.

There are also automated tools like UnusedCSS, PurifyCss that are commonly used to clean up unused CSS styles rules from CSS files.

Outcomes of writing effective code

I ran a number of performance tests using GTMetrix against different versions of the same page and found that bad development techniques increased page load time. The worst offenders were:

  • not saving images effectively for web: +28% page load time
  • using @import to call one half of a stylesheet into the other half: +7.6%
  • using inefficient CSS selectors: +8.5%
  • Sass created clutter : +16.77%
  • adding 10kb of extra HTML: +4.8%

I ran the tests using a very small page (the baseline average load time was 0.55s) and tested in different browsers.

Take the time to plan out and clean your code so it’ll remain semantic, reusable and fast.

“Always leave the checked in code cleaner than the code that is checked out.”

Wrapping Up

Writing effective code takes a lot of practice and focus during execution. To be able to write the code you should train your mind over a period of time. The hardest part is simply making a start, but as time goes by and your skillset improves, it becomes easier.

--

--