Most Essential Best Practices to Improve and Optimize Your Markup and CSS

May 19, 2013 · 25 comments

by Lars


Great looking websites that are easy to maintain and develop require high quality markup and styling. The most fundamental principle to remember is separation of presentation and content / markup and style. While separation is key you will need to have great markup to produce good CSS. This post aims at highlighting general purpose best practices for how to improve your CSS code and it also involves tips for how to work with markup. While doing the heavy lifting your self is a lot of fun, it is also recommended sometimes to look for quick solutions that still deliver excellent results. One example of this is using ready to use WordPress themes for setting up websites. One example of this could be creating an photographer portfolio using a photography theme for WordPress.



Treat markup and CSS as serious development artifacts

Good markup and CSS is time consuming to produce and minor changes or mistakes can do serious damage to you work. Like any other development artefacts CSS files should start with a well structured header and both markup and CSS files should be under at least some simple form of Revision control. Why on earth waste time on this? The main argument is maintainability and preventing loss of work if you work alone. If more developers are dependant on each other revision control / configuration management gets really critical. There are several options for getting access to software providing some basic revision control if you’re not already up to speed on that part. One of the most popular products available is Subversion. It is free and some people state that it is even better than some commercial products on the market.
Now lets take a look at what a header should include. First of all make sure it contains a title, a revision, a time stamp, and a description. You may want to add copyright and license terms as well here.

------ css -----
Copyright 2009, tripwire magazine
AUTHOR: Mr. CSS himself
DATE: 27 Dec. 2009

DESCRIPTION: Main stylesheet for WordPress theme...

Colour palette:
#555555 / Dark Grey

Don’t start from scratch every time – build up a library of elements you use often

Starting with a blank page every time you start on a new project would not be very effective and if you make a living out of it it would cost you a lot. Consider what would be common design elements for you and create a simple folder structure to store them in as you create them. You could use this to start with and extend as needed:

  • two-column layout
  • three-column layout
  • blog layout
  • print layout
  • box-layout
  • etc.

What is required to do this is to spend a bit of time stripping out non-generic elements from your work and keep the generic parts as templates for later re-use. Some people have taken this to the extreme and created whole sets of templates. You may let yourself be inspired by this but unless you plan it – don’t let this become a project in itself… Creating an index file with screenshoot like this may be useful though. If you’re a freelance designer it may also be useful to provide it for free on-line on your blog or portfolio to generate some traffic…


Nice and Free CSS Templates: This site contains free css templates for your website – Just copy and paste and there you have a stunning website !

Even more great layouts: If 53 fixed layouts were not enough here are some more both fixed and stretched layouts for ultimate flexibility. These 40 layouts are again completely CSS styled without any tables.

Fixed Length CSS Layouts: 42 free fixed length layouts ready for use

Consider and define basic guidelines and naming conventions

Having a set of basic guidelines for how to write your CSS is recommended because it will make your code more coherent and homogeneous. Basic guidelines can consist of any rule you find valuable for you and your team. I would recommend considering the following:

Using naming conventions is best practise and very common in regular programming like J2EE, .NET etc. Naming conventions is useful to govern and streamline how you name elements in you development and with CSS this is just as important as in any other programming language.

1. Hyphens Instead of Underscores: Use lowercase characters to define your class and use “-” or uppercase letters to separate multiple-words classes (ex. “main-content”, or “mainContent).

2. Use structural naming of your page segments and avoid at all cost to use presentational naming. (ex. use sidebar and not right-column). This is an important point because presentational naming binds your CSS to the markup and then the markup to the layout. This makes it really hard to move elements around with out having to rename stuff and make needed changes in your CSS. Further presentational naming prevents you from having names in your markup that actually describe what the elements are.

Taking this a bit further it is recommended to use naming that is common sense and even better commonly used in the industry. In a survey of websites of some web professionals, Andy Clarke lists the naming convention used for the structure of these sites. As you can see in the survey a few names stand out. #header and #footer are used at almost every site in the survey and #content is also very common. Why not follow trends like this and avoid making up too many proprietary names for your self? If you do make sure to use names that are intuitive and and where it is obvious what they are used for. You can see the survey here.

Use whitespace carefully but have proper indentation

Whitespace, including spaces, tabs, and extra line breaks, is important for readability of your CSS code. However, whitespace does add to page weight and you should be careful not to add whitespace that is not needed.One option you may consider is to compress your CSS for the production site. Try using CSS Drives “CSS Compressor” or YUI Compressor. Make sure you maintain a revision for maintenance that contains your comments etc.

To make your code easy to read while you work on it and if you provide it for others to maintain use proper indentation. Code that is not well structured can be almost impossible to read so it is worth the effort to maintain some kind of formatting. If you’re not good at it you should consider using a tool like CSS Beautifier. Be careful as it removes your comments but it us great for formatting segments that have ended up in a mess. Other tools that can be useful is arantius tabifier or try to check out this massive list of tools.

Structure and plan ahead

CSS is one of the most powerful tools a web developer have at his disposal but if it is not used in a clever and structured way you are certain to end up with a mess no one can use and maintain. Don’t get tempted to just drop in CSS bids and pieces as you go and try to plan the overall structure before you get started. With a few basic rules you and your CSS will be in a good shape and stay so.

1. Create the basic structure to start with (like making a disposition for a essay or book). This will be your framework and as you start adding you will know where to put it to maintain the overall structure. If you’re unsure about a specific CSS style element you should reconsider the structure and add more headings if needed.

2. Declare your most generic items first, then the not-so-generic and so on. You should start with setting up what some is calling “Master Stylesheet“. Generally this is about making required resets and overrides to make sure your CSS have a good starting point for multi browser support. Creating a strong Master Stylesheet is a complex and time consuming task that requires experience and broad knowledge. If you’re not sure where to start I’ll recommend that you kick off using the one provided here. Adjust it to your needs as you go on.

3. Depending on you type of design try to consider what the main blocks of code is expected to be (like header, main content, right sidebar, menu, footer etc.). Make sure that you apply Logical Ordering meaning that header will be in the top and footer at the very end.

You should start creating an empty structure with headers using /***** <Header Name> *****/ or /* ===== <Header Name> ===== */ (or what ever you think is looking right). It is also likely that you will find it useful to break down the structure even further and add sub sections. Lets assume you have a header section and that it consists of elements like logo, navigation etc. You could do this by using a different and less dominating header for sub sections like shown here.

------ css -----
/***** Resets and Overrides *****/
/** Global Settings **/
html, body {
body {
font:100%/1.25 Arial, Helvetica, sans-serif;
/** Headings **/
/***** Layout *****/
/** Page **/
/** Header **/

Re-use, re-use and don’t repeat CSS code

You should try to do your best to re-use attributes whenever possible. This is done by grouping elements instead of declaring the styles over and over again for each element. Fx. if h3 to h5 elements all share certain styles you should group them using commas. Doing this will save you 30 or more lines of code and the overall maintainability will be greatly improved.

------ css -----
h3, h4, h5{
 color: #000000;
 font-size: 14px;
 font-weight: bold;

Other elements where you typically will use grouping is for different states of navigation and links. While color may change on hover all other styles may be the same.

Use Shorthand properties

Like grouping elements to re-use styles makes you write less code you should always use shorthand properties. Several key CSS properties that you use over and over again support use shorthand: margin, border, padding, background, font, list-style, and even outline (notice that this is not an extensive list!). Lets take a look at some exambles:

----- markup -----
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Nulla dolor purus, lacinia a placerat non, malesuada a lectus.</p>

------ css -----
p {
margin-top: 5px;
margin-right: 10px;
margin-bottom:  15px;
margin-left: 20px;}

//should be replaced by:
p { margin: 5px 10px 15px 20px; }

Rules applied for margin:

To get an over view of the shorthand notation available you may want to check out this cheat sheet or this article giving useful examples:

Set up your typography in CSS

Should be clear to anyone that applying style (fonts, size, colour alignment etc.) directly in the markup is bad practice and not a durable solution. It may look right but it’s a pain to maintain. OK while this is obvious other elements of typography may not be. Typical Typographic effects in CSS are: Type Size, White Space, Typefaces, Case, Style, Color, Alignment
Example: Having only CAPs in headers or menus is typography and should be left to CSS.

----- markup -----
  <li><a href="/">HOME</a></li>
<!-- should be -->
  <li><a href="/">Home</a></li>
------ css -----
ul li a {

Use proper nesting of elements

Some elements are block elements and others are in-line elements and you should always respect this and nest in-line elements like <a> inside fx. a heading <h1>. It is a common error and most browsers will handle it well but it is not right. Validating your code will catch this kind

Block style elements

<div>, <h1> … <h6>, <p>, <ul>, <ol>, <dl>,<li>, <dt>, <dd>, <table>, <blockquote>, <pre>, <form>

In-line style elements

<span>, <a>, <strong>, <em>, <img />, <br>, <input>, <abbr>, <acronym>

Validate validate validate and fix…

Before putting a new design live you should validate that your CSS is OK and get rid of any mistakes you may have made. They may not have any impact on how the page renders in the browsers you use to test, but should be eliminated to make the product final and perfect. The good thing about validating is that you most likely will learn from the feedback the valitator provides. Relevant tools:

Document your work

Documentation is essential we all know that. Still mot developers consider it as a task that should be avoided at all cost. The effort put into documentation and the quality delivered is always controlled by the client requirements, the budget, the time available etc. But don’t try to avoid it completely. Making just enough documentation have several benefits but defining just enough may be hard. 1) It makes you go through the work you have done. Reviewing makes you recall the solutions you have come up with, problems you solved etc. and taking some notes on this may help you remember and bring it back for reuse at a later point in time. 2) whether its a contractual obligation or not maintenance is important and in a busy work environment most people will not be able to remember enough for providing efficient maintenance after just a few projects.

In-line documentation

First thing you should take serious is in-line comments in the CSS code. Remember that you may need to compress the CSS for production as explained earlier but self documenting code is a must. In most project in-line documentation will be just enough.

----- markup -----
<!-- In your HTML this is how you insert documentation in the code -->
<div id="header">
<!-- Header Start here! -->
<!-- Header End here! -->
------ css -----
/* In CSS this is how you insert documentation in the code */
/***** Setup *****/
 border: 0;
 margin: 0;
 padding: 0;

Markup and CSS documentation

If you’re developing templates or layout for larger solutions and applications it is recommended to write regular documentation as a supplement to in-line documentation. The structure and template used may vary depending on your preferences or the organisation you’re working for but the elements that makes sense to document would be more or less the same. One of the problems with regular documentation is to keep it up to date as the world moved on in a sprint. The obvious solution is to build the documentation using automatic generation (ex. javadoc, model driven development etc.) or in this case use the CSS for the solution being documented to build the documentation. All you need to do is creating a markup that make use of all the layout styles and explain how they are used and if certain rules should be followed – ex. headings:

Created once you will have a markup document that you will be able to re-use with minor adjustments. An example you may want to check out is mezzoblues markupguide.

{ 17 comments… read them below or add one }

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

{ 8 trackbacks }

Previous post:

Next post:

Web Analytics