Category: Code

Responsive tables using CSS

As the world of web design has embraced CSS (and, indeed, become more aware of Accessibility) designers have become, in many ways, rather scornful about the humble HTML table—especially as responsive tables are so tricky.

As with every HTML element, there are good, semantic reasons to use tables in certain circumstances. Or, rather, in one circumstance—when you are displaying tabular data.

So far, so good.

The non-responsive solution

However, in our multi-device world, tables do provide some challenges—particularly on small screens. The simplest way to address the issue is, as Twitter Bootstrap does, simply to surround the table with a div that has overflow-x:auto; applied on small screens.

This has always struck me as being rather inelegant: it is a hack, a work-around to enable people to see tables as they would be displayed on the desktop, rather than a truly responsive solution.

So, I thought that I’d share two different solutions that I have used (and continue to use) for responsive tables. I don’t claim to have invented either of them—I have seen similar solutions elsewhere—but I thought that my particular twists might help others.

Hiding columns with the Checkbox Hack

In my day job, we often have to generate pages that display quite large tables—such as a tenant’s rent statement. These will have, say, seven or eight columns, e.g. date of payment, several individual charges, the total charge, and the remaining balance.

The first thing that I did was to talk to the customer, and get them to survey their tenants to find out which were the most important pieces of data. Armed with this information, I used @media queries to hide all but the most important columns on small screens. Thus, when accessing their account through a mobile, the tenant was presented with the date of payment, the total payment, and the remaining balance—the three of which fitted easily without horizontal scrolling.

Crucially, however, if they wished to see other columns, then they could switch columns on and off as desired. And all of this was achieved using only the CSS Checkbox Hack, as demonstrated in the Pen below (this example is not responsive, but you can use the label buttons to switch columns on and off).

See the Pen Table sizing and checkbox toggling by Chris Mounsey (@devilskitchen) on CodePen.

This is a nicer solution than the scrolling div, since it does allow the user to focus on the important information—and, in this type of case, it may even be the best solution.

What do you do when you cannot separate the columns of primary importance? And how do you craft a truly responsive table?

Pivoting the table using data-attributes

The neatest solution that I have adopted is one in which we use data-attributes to replicate our headings, and then simply pivot the table.

In order to achieve this sort of responsive table, we first add the column title to the relevant cells (this does imply a slightly larger HTML foot-print, but you are GZipping your website, right?). So:

Now, we use @media queries to apply the following CSS for small screens (obviously, I use LESS, but I’m showing the CSS for those of you who aren’t familiar with pre-processors).

After that, all you need to do is to use standard CSS to make things look prettier. The Pen below shows one of my more recent efforts: resize the window to see the responsive table pivot (there is a desktop, a tablet and a mobile state).

See the Pen Responsive Table by Chris Mounsey (@devilskitchen) on CodePen.


I think that both of the responsive table examples above work better any others that I have so far used. As outlined, which one of these I use in production rather depends on the purpose of the table.

However, I hope that this quick post gives you some ideas about designing truly responsive tables.


Two years ago, I tried to implement our web software interface using flexbox. Unfortunately, I was a little too eager in this endeavour, and had to hastily reinforce my fallbacks as the specification changed.

The Flexible Box Layout Model—commonly known as flexbox—has the potential to solve a number of perennial problems that front-end devs have been banging their heads against ever since CSS was invented in 1996, including equal height columns, true proportional width flexibility, and DOM ordering over-rides (very useful for Accessibility).

A number of these practical problems—and how flexbox solves them—are illustrated on Philip Walton’s Solved by Flexbox GitHub page.

However, as I discovered back in 2011, flexbox has had rather a chequered history—passing through three distinct specifications. Detailed support is outlined at, but, roughly, browser support is:

  • flexbox-legacy: supported by Safari 5–6 and Chrome 4–20;
  • flexbox-intermediate: Internet Explorer 10;
  • flexbox: Chrome 21+, Safari 6.1+ (allegedly), Firefox 21+ (sort of: there’s no support for flex-wrap and flex-flow).

To make things more complicated, Modernizr only has feature-detection for the oldest and newest syntax, which are output as flexbox-legacy and flexbox respectively.

And finally, once you delve into all of the possible variables, the syntax is not at all simple.

Luckily for us, a number of very smart people have been keeping up to date with all of the progress and built some useful web tools to generate code for us.

  • Flexyboxes provides a neat WYSIWYG interface for building flexible layouts, and it will generate code for all three syntaxes if you need to. Do be careful, however, as the older versions are not as capable as the up-to-date flexbox.
  • You can only use Flexplorer if your browser supports the latest syntax (which Safari 6.0.2 does not!), but it does also give a useful rundown of browser support for vendor prefix requirements.

With everything settling down—and a UI refresh of our software on the cards—I have been considering writing a set of LESS mixins for deploying flexbox in the wild. Inevitably, of course, putting “flexbox less mixins” swiftly shows that yet more smart people have got there first.

With so many to choose from, David de Coninck’s version jumped out at me most immediately—his use of guard expressions is really elegant.

See the Pen Flexbox 2013 LESS mixins by David De Coninck (@davidgenetic) on CodePen

Do you have a favourite LESS mixin that supports all of the syntaxes out of the box? Let me know in the comments…


Reciprocity: give to get

Living in the world that we do—with its smartphones, transatlantic travel, ultra-high-def TVs and One Direction—it’s sometimes easy to forget that we are, at the most basic level, animals.

We have, over the course of human evolution (modern humans it’s generally agreed upon have been around for at least 200,000 years), carried with us various traits that helped our long gone ancestors to navigate and survive on this planet we call “home”.

In the modern world of communications these traits may seem of no real concern to us but the truth of the matter is that we still act and make decisions based on them.

The use of reciprocity, for example, can be a powerful tool to help create a reaction and a connection with your clients and customers. It can help build a deeper relationship, creating trust and loyalty.

At the most basic level, reciprocity is the exchange of something of value between two or more people. This doesn’t have to be as obvious as giving a present or receiving a birthday card: assistance, advice and contacts can equally be a form of reciprocity.

By and large we try to repay in kind what another person has given us; if we don’t, we usually have an overwhelming feeling of guilt—and there aren’t many people who enjoy that feeling. I know I don’t.

There are many theories as to where reciprocity comes from and why it’s a major influence over our lives and decision making. It has been theorised that it relies on a universally held belief of future obligation: if we give something of value away it won’t be lost forever but will be repaid to us in the future with something of equally valuable (or even more so). Humans for the most part will almost always strive to repay this “debt” even when the expectation of repayment is a vague one.

We can see reciprocity happening all the time in the online arena—take LinkedIn, for example. When we receive endorsements or recommendations from our clients or associates, most of us will respond in kind without being asked—we somehow feel compelled to do so.

When someone comments on one of our photos on Facebook, we will often comment back on one of theirs. Even if we don’t feel obligated, we would rather do this than not as it’s fundamental to our social success.

We can make use of this ancestral practice in a variety of ways.

  • Write free articles—not only will you be giving your readers knowledge for free but you’ll also be enhancing your position and credibility as an expert in the field in which you operate. The same can be said for coding. There are many developers who use reciprocity by giving away bits of code they have created: those who download the code feel obliged to either spread the word about the developer’s site, leave comments of thanks (usually praising the developer’s skills) or offering solutions or “bug fixes” for free.
  • Offer a free consultation—by giving away a bit of your knowledge and helping your potential clients/customers just a little it will instil the feeling that you’ve gone out of your way to help. It will enhance your reputation and increase the prospect of a more meaningful and prosperous relationship.
  • Compromise—by showing that you have the ability to compromise, your client will more than likely wish to reciprocate in kind, leading to a mutually beneficial outcome. This doesn’t mean that you have to become weak and go against your fundamental principles. Be strong, but always make room for compromise too.

It seems that even though we are moving full steam ahead into the future, there are certain traits that are ingrained in the collective human psyche. Don’t forget to use those traits—they’re effective, they work and they have done for at least the past 200,000 years.

Applications that I use

Having mentioned Sketch in my previous post, I thought that I would expand on the applications that I use in my workflows. And to start with, I need to expand on what those workflows actually are.

Which is tricky—because I do quite a number of varied jobs.

First, I do a considerable amount of management, both in my team and in the wider business. This is why my job title is the, slightly unwieldy, Creative and User Experience Manager (usually shortened to CrUX Manager).

Essentially, I lead the team that designs and builds our customers’ websites and intranets on our company’s content management platform (CMS). However, I also design the user interface (UI) and user experience (UX) for the CMS—plus I also design a lot of the new functionality too.

Occasionally, I give talks at events—both internal and external—about the web, CSS, Accessibility, and other related issues.

Because I know a lot about the web, our product and our customers, I have also spent a lot of time in customer pitches, Information Architecture (IA) workshops, and in discovery meetings for new software. In other words, I am heavily involved in a customer’s entire journeys with our company—and, in many cases, for determining the steps along that journey.

And, since I run the CrUX team, I am also responsible for recruitment to that team and, with the operations team, for managing resources on a day-to-day basis. And, of course, when we have a new starter, I am responsible for sorting out software and hardware—which means that I know how much we invest in our applications!

Which brings us back to where we began—the applications that I use to achieve all of this.

Graphic Design

For the moment, I find myself continually coming back to Photoshop—like a dog to its sick. I don’t really like Photoshop for design (and I loathe Illustrator) but it is familiar and thus relatively easy to dip into.

However, I am gradually weaning myself off Adobe’s products in favour of smaller, cheaper applications that are, in many ways, better for the job than Adobe’s bloated behemoth’s.

I have been playing about with Sketch (about £30) a lot, and I think it’s a wonderful application. It is very capable and, with every update (usually monthly), it becomes more capable and more stable. I am aiming to make it my primary design tool.

For non-vector based work, I have been getting into using Pixelmator (about £20) which is also an excellent (and cheap) photo-editing and design application.


My browser of preference is Safari. Its Web Inspector tools are almost as capable as Chrome’s, and I find the browser faster and more reliable than Google’s offering.

However, I do test in all major browsers—including Internet Explorer 7, 8, 9 and 10. To achieve this on my Mac, I use VirtualBox (free) and the wonderful IEVMS script to automate the conversion of Microsoft’s supplied disk images to a format that VirtualBox can read.


A few years ago, I found myself, with a colleague, in a café with free Wi-Fi; up until that point, I had used Dreamweaver to code my work. However, my laptop was not equipped with my meatier applications and so—needing to do some coding and having read a good review of it—I downloaded Panic’s Coda.

And I have never seriously used another coding environment since (although I have also dabbled with MacRabbit’s Espresso—before they merged it with CSS Edit). I certainly never launched Dreamweaver ever again.

Coda was, essentially, my first foray into the sunlit uplands of indie Mac Developers. Up until that time, I had basically used Adobe applications and little else; for someone with this experience, the speed with which Coda launched and operated, as well as its feeling of lightness, were a revelation.

That independent developers are challenging Adobe in its core areas of photo-editing and vector design (this latter being an area that Adobe basically stole when it killed my beloved Freehand) is one of the very best things about the Mac platform right now.

I write in LESS and use the excellent CodeKit to process it, as well as for compressing images, and other useful things. Be sure to read CodeKit’s amusing release notes, by the way…

Finally, I started using CodePen a lot for experiments, reduced test cases, reference files, etc. I particularly like the fact that it compiles LESS on the fly. I haven’t had much time to continue playing with it recently, but that should change in the next few days.

Software Design

My role in this area is, essentially, to gather customer needs, to productise them, and write requirements specifications.

For this I use Apple’s Pages (£14) for the text and, for the workflows, Celestial Teapot’s very nice little diagramming application called, simply, Shapes (roughly £3!).

This latter app is—like most Mac indie apps—under active development and Celestial Teapot seem very good at taking feedback and incorporating it into releases.


For most other administrative tasks, I use Pages, Numbers and—for presentations and speaking engagements—Keynote.

When presenting, I use Apple’s Keynote Remote—running on my iPhone—to control the slides and display presenter notes (where necessary). In the absence of Wi-Fi (a rare thing these days) I carry a standard, hardware Apple Remote.


I do dabble with a few other apps, and I like to try out new applications quite often.


Where necessary, I use MockingBird for building up wireframes; it is simple, elegant and easy-to-use. The lack of development on it over the last couple of years has been disappointing, but it is still an excellent online application.


One app which has a great deal of potential is Tumult’s Hype. Using this application, you can build up complex animations using a timeline model, and Hype will then generate a file containing CSS3 animations (including complex matrices): even better, it will also generate the Javascript required to cater for older browsers.

Combine this with Modernizr and the built-in YepNopeJS, and you have a modern, compliant solution for creating complex animations.

Project Planning

Since I have taken over my current job role I don’t use OmniPlan as much, but I still find it useful for internal scheduling: it’s a fully-fledged project management application, with proper concepts of utilisation and efficiency.

Font Management

For font management, I still use the free version of Linotype FontExplorer X (which, whilst difficult to find now, has lasted me for years and years!), but I am starting to switch over to Bohemian Coding’s Font Case.

For web fonts, I use TypeKit (although, since Adobe has taken over, I am finding some issues with reliability. What a surprise) and, occasionally, Google Web Fonts.

And that’s about it. There are one or two applications that I play with, but the major ones are those listed above.

Do you have any favourite applications? Feel free to leave your preferences in the comments…

Removing comps in web design

For a few years now, I have had the feeling that we are approaching web design in the wrong way. Many designers—and their clients—have made the transition from the medium of print, and transferred the design processes too.

In print, we were all used to producing proofs with millimetric—nay, pixel-perfect—precision because we had to: the high-resolution of print meant that that one pixel gap was obvious when the material came off the press.

But it made absolute sense to produce these proofs—or composites (“comps”)—because print is a fixed medium: what you see is, pretty much, what you get.

Building a nightmare that never stops

Hence the bane of the website builder’s job: a pixel-perfect Photoshop comp married—in Hell—with a customer who doesn’t understand that their website is never going to precisely match that beautiful image proof that they have signed off.

The web has always been a fundamentally fluid medium: in print, the amount of text was often governed by the size of the printed page—in web design, the very opposite is true.

And this point is compounded when designing for a content management system (CMS), where the designer could not—and should not—absolutely control how much text a user can insert.

The death of the static image comp in web design

As such, I really believe that we need to kill this idea of using static image comps in web design and, a few weeks ago, Brad Frost succinctly summed up why in a post entitled The Post-PSD Era

Throughout my career, I’ve watched immensely talented designers waste a shitload of time creating fully fleshed-out comps of what a website could look like. Pixels get pushed, details are sweated, pages are printed out, hung on walls, and presented to clients. Clients squawk their feedback, then designers act on it. They repeat this dance until everyone is content (or until nobody gives a shit anymore, which happens more often than you’d think).Only then do those pristine comps get handed (more like shoved) over to developers to build.

It’s an increasingly-pathetic process that makes less and less sense in this multi-device age.

As it happens, Brad wrote this post at roughly the same time as I was presenting a new design process to my fellow managers—and I found it when looking for some pithy comment with which to populate a slideshow presenting said process to the rest of the company.

Bringing it home

My company designs and implements websites on its own Content Management System (CMS). I have moved through different positions within the company over the last five years, but I was put in charge of the new Creative and User Experience Team in July.

In between delivering customer projects, I have been attempting to make our processes more efficient. It swiftly became obvious that there were a number of problems with the way in which we designed and build our websites and intranets.

Improving our process: driving efficiency

The first has been largely improved by the adoption of an increasingly robust CSS LESS framework.

The second, however, was more difficult to address—customers’ expectation that their websites would look precisely (yes, even in IE7) like the lovely images that they had signed off .

We were also duplicating work.

So, the first thing that we did was to push the responsibility for producing wireframes solely onto the Information Architects; wireframes were already an output of these workshops (driven largely by the Attention Mapping exercises), so duplicating this work seemed ridiculous.

Next, we created a selection of mood boards—with recognisable, non-techie names—which, combined with the wireframes, enabled our designers to get a very good idea of what the customers were aiming for.

Zombie comps that will not die

But, at the end, we were still producing fixed image comps that were taking too long to create and, importantly, amend. Customers were getting hung up on the positioning of elements when, in our CMS, you can place anything anywhere (just about).

So, in December, I my research turned up Samantha Warren’s—a website dedicated to promoting the use of said Style Tiles.

Style Tiles are similar to the paint chips and fabric swatches an interior designer gets approval on before designing a room.
An interior designer doesn’t design three different rooms for a client at the first kick-off meeting, so why do Web designers design three different webpage mockups?

Style tiles are for when a moodboard is too vague and a comp is too literal. Style tiles establish a direct connection with actual interface elements without defining layout.

The sites and systems that we build are huge.

There is simply no way that we can proof up all of the pages that make up the tens of functional Modules that our customers may have bought.

Style Tiles and a way forward

As I saw it, Style Tiles—with a bit of modification—would enable our company to provide the important elements to our customers (the look of a menu system, how a Staff Directory entry might be displayed) without them getting hung up about where on the page these elements might appear.

After all, not only is the web a fluid medium but our CMS also gives the customer total control over their page structure.

With Style Tiles, clients could focus on the important details, rather than getting hung up on where those things appeared on a page. We would, in fact, be aligning our processes with the flexibility of our product and thus reinforcing its superiority.

There were, of course, other benefits, including being able to turn around work much more quickly and thus increase the productivity of the team.

It’s never enough…

But Style Tiles wouldn’t be enough—especially in the age of Responsive Design.

As such, we decided to build Live Prototypes alongside the Style Tiles. With our LESS framework (which has mobile @media break-points built in), and the CMS’s inbuilt styling options, this became a viable proposition.

The first run is scheduled for Tuesday morning: I’ll let you know how it goes…

A new CSS property — position:sticky;

My blog colleague, Mike, wrote about implementing “sticky” menus in Javascript; however, it seems that this effect can be achieved in WebKit browsers through a new CSS property—position:sticky;.

By simply adding position: sticky (vendor prefixed), we can tell an element to be position: relative until the user scrolls the item (or its parent) to be 15px from the top:

At top: 15px, the element becomes fixed.

HTML5 Rocks has put together a demo although, of course, it will not work in anything other the latest version of Chrome or the WebKit Nightlies.

However, I can think of a couple of places where I should incorporate position:sticky; into our company’s CMS and shall do so, against the day when the property is widespread.

As a point of interest, this tends to be my general strategy for new CSS properties: I implement them into our systems so that, in the future, people get a nice surprise!

UPDATE 18/05/2014: position:sticky; seems to have appeared and disappeared more often than a flexbox spec. However, Can I Use reports that position:sticky; is supported on  Safari 6.1+ (on desktop and iOS) with the -webkit- prefix, and that support is coming to Firefox and Chrome in the near future.

Sticky Navigation Bars

A key consideration I make when designing intranets is how the navigation must always be easily accessible because users can land on any page and each user will have a different set of aims when using the site. Links are sent over email all the time and I can’t expect the sender to clean up a URL to remove things like anchor references or variables.

The solution: sticky navigation bars.

The effect is simple. When a user scrolls down the page the navigation is seemingly ‘lifted’ out of it’s placeholder and flows down the page with them, allowing them to click through to any other part of the site (so long as it is held within the primary navigation system).

The method was also remarkably simple, thanks to a jQuery plugins called Waypoints.

I’m using WordPress for my intranet project, so the code I use in my header.php file is:

The vital thing here is the containing element being set to use the nav HTML tag and the menu class being set to nav-bar.

Then in footer.php we call the Waypoints plugin. I put these JS calls in the footer because if they hang or fail the user can still use the website, albeit without the sticky nav. I’ve also added my site-specific code to a separate JS file because I like to keep things tidy. Don’t forget this is all jQuery so you’ll need to call the core files too.

I also do some really simple css.

Then, inside stickynav.js I do this:

Easy, huh? Credit where it’s due, this is not my own solution it’s my implementation of a tutorial here.

Web Fonts

Adobe have just recently announced the release of Adobe Edge Web Fonts, a large library of web fonts. Whilst Adobe has teamed up with Google in order to offer many of these typefaces, they are served through TypeKit—which was bought by Adobe some months ago—and are free to use (for now, at least).

I am a great fan of using web fonts—anything has to be better than constant doses of Arial. There are certain pitfalls and caveats that web designers do need to bear in mind, but I shall cover those in a later post.

Right now, I would like to make an observation—simply because it amuses me…

Ten years ago, companies were getting frustrated that they couldn’t use their super print-specified corporate fonts on their websites (at least not without using some horrible substitution system like Flash or Cufon).

So, in the last few years, we have seen more and more companies changing their corporate image—and all of their print and branding material—to one of the 30-odd typefaces available to “normal” web browsers (such as Trebuchet or Lucida).

Now, the web font revolution has hugely expanded the number of typefaces available on the web—rendering all of the rebrands utterly unnecessary!

I am most amused…

How browsers build pages

There are any number of guidelines and theories about how best to write sustainable CSS, and smacss (pronounced “smacks” apparently) is another of those. I was reading through the introductory chapters, and was interested to learn how browsers build pages.

The browser starts at the top and sees a body element. At this point, it thinks it is empty. It hasn’t evaluated anything else. The browser will determine what the computed styles are and apply them to the element. What is the font, the color, the line height? After it figures this out, it paints it to the screen.

Next, it sees a div element with an ID of content. Again, at this point, it thinks it is empty. It hasn’t evaluated anything else. The browser figures out the styles and then the div gets painted. The browser will determine if it needs to repaint the body—did the element get wider or taller? (I suspect there are other considerations but width and height changes are the most common effects child elements have on their parents.)

This process continues on until it reaches the end of the document.

This seems, to me, to be a very inefficient way of building a page since multiple “repaints” are necessary, but it is easy to forget just how fast and efficient modern browsers have become.

Below, you can view a vastly slowed down video of a Mozilla browser rendering a page using this method.

Pretty impressive, I think. But it still seems conceptually inefficient…

Using local colour variables in Less

One of the most time-consuming aspects of website design is when the customer wants multi-coloured menus—and for those colours to cascade through the other attributes on those site areas. This can involve lots of different selectors, and having to change them all to different colours can be a pain—and this is where using local colour variables in Less can save lots of time.

Standard colour variables

Consider the following set of declarations:

Now, imagine that these all had to be altered depending on the .site-area-x, and that we have huge number of selectors to restyle.

Obviously, we could simply declare our @color2, but then we have to go through and change the colour in all of the other declarations too.

And this needs to be done for each one of the eight different menu areas—it’s going to be pretty time-consuming.

Local colour variables to the rescue

There is a better way in which to do this—by using local colour variables. Consider the following set of declarations:

We now only have to change two attributes—the .site-area-x class, and the @site-area-colour.

OK, it’s not entirely automated, but it will take considerably less time than the first method.

Website wireframing

Some time ago I became a Beta tester of a website wireframing tool called MockingBird; our company has used it as a wireframing tool for some years now, and it has always served us very well.

MockingBird is an HTML5 application that enables collaboration on projects, and is extremely easy to use. This ease of use is partly conferred by the smallish number of widgets within the application.

As websites get more sophisticated, however, this selection of widgets seems a little limiting; personally, I had expected the creators to add more options after the formal launch of the application. They have not done so, and the blog has not been updated since December 2010.

Whilst I am not about to jump ship just yet, it seems natural to look around for other alternatives for our website wireframing needs, and so I followed a link to Moqups—another HTML5 website wireframing application, and apparently free.

I haven’t then experimented with it, but it does seem to have reasonable features—and a somewhat more design-oriented set of widgets.

But why have they adopted the awful kind of hand-drawn typeface for the text? It embodies everything that is awful about Comic Sans without actually being Comic Sans…

Generate a table of contents using JQuery

One of the under-used features of our company’s CMS is Virtual Documents: these are actually large HTML documents that can also be displayed and managed within the Media Manager in the same way as a “physical” file (such as Word or PDF). However, one of the ways that Virtual Documents could be made far more useful is through the ability to generate a table of contents.

Virtual Documents came about because one of our customers had a huge document library in Lotus Notes: they wanted to import these documents into our CMS, but maintain all of the permissions and access rights already applied.

The entire library was exported as XML-based PDFs, and we then wrote a parser to interpret and import the content (complete with styles), and also to gather and apply all of the access rights. The resulting imports became known as Virtual Documents.

A number of our customers have been interested in Virtual Documents, but felt that some features were lacking; one of these was pagination, but this could be by-passed by creating a table of contents that was derived automatically from the headings—as, indeed, Word and Pages do.

There has not been enough demand for us to devote heavy resources to this aim within the product itself, so I started looking around for front-end solutions. And I found a post by Janko at Warp Speed which details how to built a table of contents in JQuery.

It will need some tweaking to get it to behave with our current structure, but I believe that it is a very decent solution—especially the final scaled and fixed table of contents demo.

Writing sustainable CSS using SOLID principles

We all know what it’s like: you start off with the best of intentions—to write neat, sustainable CSS using all of the very latest fashions (DRY, OOCSS, etc.)—but then the clock is ticking and you find yourself rushing the project and producing a stylesheet that, whilst not totally awful, still resembles spaghetti.

This is a problem that only becomes compounded when you are writing Less: here the problem becomes one of lazy nesting and, next thing you know, not only do you have selectors that are 80,000 characters long but you have also “cemented” certain elements—you know that if the customer moves that slideshow from that position on that page, then the whole thing is going to fall apart.

Leaving aside the special considerations that you need to bear in mind when implementing designs onto a large CMS (which I intend to address in another post), writing sustainable CSS is absolutely essential to a web designer. The simple fact is that sites with well-written CSS will load faster, be easier to maintain (essential if your customers are regarded as partners), be more flexible (from a CMS point of view) and be generally more elegant.

Introducing SOLID Principles to sustainable CSS

There are, of course, many opinions as to what makes sustainable CSS: however, one of the best articles that I have read on the subject is this post on SOLID principles by Miller Medeiros.

SOLID is an acronym for five basic principles of object-oriented programming and design that when applied together can make systems easier to maintain and to extend over time. The term was coined by Uncle Bob and I’m pretty sure he didn’t had CSS in mind(although I didn’t asked him).

  • Single Responsibility Principle
  • Open/Closed Principle
  • Liskov Substitution Principle
  • Interface Segregation Principle
  • Dependency Inversion Principle

Now, this all sounds a bit too techie for me, but Miller goes on to explain the principles in  rather more detail.

Single Responsibility Principle

This principle states that an object should have only a single responsibility, and that responsibility should be entirely encapsulated by the object. When applied to CSS this means that we should separate structure from presentation, instead of creating a single class and/or element that does both, we should decouple them so you can change the skinning of the components without affecting the structure.

CSS rules should have a high cohesion, you shouldn’t normally see too many different kinds of rules grouped together. You shouldn’t have text styles + borders + colors grouped with dimensions + positioning and floats.

By doing so we can reuse the same modules inside a different container and increase the chance of reuse. It will also make maintenance easier since you can change the skinning without affecting the structure and can toggle the visual easily based on the context (eg. element with same structure but different colors).

This principle sounds sensible enough—and its particularly easy to address when using CSS pre-processors—but, in fact, it is usually the very first method to go out of the window when you are under pressure to deliver.

Open/Closed Principle

“software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification”

That means that you should make it easy to overwrite/extend the base rules and should avoid editing the base classes.

You should only edit a base class if you are fixing an error, never add new behavior, otherwise you might introduce conflicts. That means that you should not change yourreset.css file or edit rules that affects multiple elements after the project is stable. Create a new class that augments it instead of editing it.

This is an easy principle to stick to, since it can save a lot of time: with the capabilities of Less, I quite often find myself writing things like this:

In Sass, you can use the @extend  class to do this even more sustainably. If you aren’t already doing this, then I heartily recommend that you adopt this methodology.

Liskov Substitution Principle

“objects in a program should be replaceable with instances of their subtypes without altering the correctness of that program”

Classes that @extend others shouldn’t have a different behavior than the base class. You should be able to toggle between them without affecting the correctness of the app.

The idea behind this principle is that if you can swap Parent classes with their Children, without causing any undesired side effects, you will have a system that is more flexible and easier to understand. It will increase code reuse on cases that you couldn’t predict when the project started.

That means, modifiers should ideally affect only things that wouldn’t break the layout. If the base class doesn’t have a fixed height the child class shouldn’t have as well, the display and position also shouldn’t be changed.

Once again, this is a sensible principle that, again, often falls by the wayside.

Interface Segregation Principle

“many client specific interfaces are better than one general purpose interface.”

That means, it’s better to have multiple specific base modules than to have a single generic one. It will increase the cohesion of your modules and make code easier to refactor/change/maintain (since it reduces tight coupling).

Now, it has to be said that Miller does not seem to be entirely on board with this principle, or what it implies.

Sometimes it can be really tempting to create a base module that fits multiple scenarios trying to increase code reuse as much as possible. To be honest, lately I’ve been thinking that not all code reuse is a good thing. If you are doing it just for the sake of reusing(specially CSS) you might be increasing the coupling between modules without a need, that will make further changes harder to implement since it will cause a ripple effect to undesired modules (eg. changing the margin around an article in the homepage would also affect the margin around a blog post on the inner pages).

Which is fair enough.

Dependency Inversion Principle

  1. High-level modules should not depend on low-level modules. Both should depend on abstractions.
  2. Abstractions should not depend upon details. Details should depend upon abstractions.

I like to think this rule on the CSS domain means that the container shouldn’t care about the existence and the visual style of its children as long as it behaves how it expects it to behave. For an .article component it shouldn’t matter how the .title is styled, as long as the title doesn’t break the layout. We should delegate the styling of child components to their own modules and do it in a way that the child elements can be swapped without affecting the parent element. This is the core idea behind OOCSS.

Nested selectors are a sign that you might be breaking this rule. Instead of making nested selectors like #sidebar .group > h3 you should create a new class .group-title. That way it can be an <h3>, <div> or any other element you need. It will be easier to create new modules with slightly different styling/behavior by simply swapping the dependencies (child elements). This also favors composition over inheritance.

It also couples with an absolute principle that I advocate: that you should avoid targeting the mark-up element whenever possible—especially in these days of shifting HTML5 specifications!


I have been adhering to most of the SOLID principles for many years without really knowing about it, but this article is extremely good at articulating why I have been coding in the way that I have.

Over the years, I have had to dive into far too many website implementations and then recoiled when I have seen the state of the CSS (let’s leave aside the HTML for the moment).

These experiences have convinced me that one of the most important issues facing our company—if not the web as a whole—is the production of sustainable CSS.

Using Less as a live CSS engine

Following on from my last post on CSS pre-processors, there is an interesting guest post over at CSS Tricks—from Andrew Powers of PageLineson using Less as a live CSS engine.

It seems that PageLines—who craft WordPress Templates—actually use Less as a live CSS engine for enabling customers to change settings in their templates.

How we implemented it

For us the the key to executing a live LESS engine was this port of the LESS processor to PHP (link) which allowed us to parse and cache LESS files based on user action on our server. To get this working the framework just does the following.

  • Grabs all the LESS files throughout the framework and adds them to a PHP variable
  • Uses the above PHP script to parse the LESS into CSS and puts it in a variable
  • Outputs the CSS to a file which is cached both on the server and on visitors browsers
  • The process is run again whenever a user saves their settings or installs a new extension

This is extremely interesting because, ever since I started using Less, I have been contemplating using it for precisely the same thing within our company’s CMS.

Right now, our CMS uses a very advanced Dynamic Templating System (DTS) which reconfigures the page depending on what the user has placed on it, i.e. if you place a widget in the left-hand column, then it will generate a left-hand column; if you don’t, it won’t.

However, currently, all of the aesthetic styling has to be done by our own implementers; however, with the advent of multi-site functionality in our CMS, we are seeing an increased demand for advanced users to be able to make changes themselves.

Although we have implemented a system where aesthetics can be saved as Custom Style Presets—which can then be applied by the user—we have to write those presets first.

Ideally, we would actually allow the user to change certain colours themselves—but that leads to all sorts of complications that, in the end, would constrain our designers and deliver only partial control to the user.

Using Less as a live CSS engine is the way to get around this problem. However, since our system is not written in PHP, we would need to see if Less has been ported to ColdFusion (unlikely) or write the plugin ourselves (not currently a priority).

Whichever way we go with this, it is nevertheless great to see that there is an operating version of this concept being deployed in the wild.

CSS pre-processors

I discovered CSS Less about eighteen months ago (although I forget how) and began using it almost immediately: the power and flexibility of CSS pre-processors over the standard CSS language are immediate winners.

The real problem with CSS is that it is, by its very nature, a static language: it isn’t compiled by the browser—which makes rendering very fast, but limits the possibility for time-saving features such as variables.

And although the CSS Working Group have released a Draft Specification for CSS Variables (and WebKit has implemented it), the syntax is pretty clumsy to say the least.

So, for an increasing number of front-end developers, using a CSS pre-processor is becoming incredibly important. There are two main languages to choose from—the aforementioned Less, and Sass—but both share some common traits.

Both were written as Ruby Gems, both introduce time-saving concepts—such as variables and mixins—in syntactical extensions of CSS, and both feature compiling engine that “watch” your files, compiling them to CSS on save.

The mighty Chris Coyier wrote an article comparing both engines in which he came down firmly on the side of Sass: looking at his arguments, and code that I have seen in the wild (on CodePen, for instance) I accept that, logically, Chris is probably right.

However, for me, Less is the better language, and there are a few reasons for this:

  • although it originally started as a Ruby Gem, it wasn’t long before it had been ported to Javascript. Whilst JS is not my forte, it does mean that you can deploy Less on a live site (or, rather, during development): my colleagues and I deployed this method when lots of us were simultaneously implementing a site during 2011’s GiveCamp;
  • when I started investigating pre-processors, the talented Brian Jones had written a free Less compiler app for Mac OS X which meant that I didn’t have to muck about with the Terminal to get things set up. I now use his invaluable CodeKit application for all my compiling needs (although it does much more than just compile, e.g. image compression);
  • the Less syntax feels more CSS-like to me. As someone who is both very busy and entirely self-taught—as well as not being a natural “process” coder, this is an important point. It makes Less very quick for me to write, and to take advantage of the power of it very easily. (And I am only just tentatively scratching the surface of Less’s more powerful—and more code-like—features, such as Guard Expressions.)

Ultimately, it is entirely up to you which pre-processor you feel most comfortable with: but if you do any CSS work, you should definitely be using one of them. Here are just a few examples of the power that CSS Less gives you:

Variables (with colour operations)


Variables are worth the price of admission on their own, especially when combined with colour functions such as lighten, darken and fadeout.

We have saved substantial amount of time in implementing sites on our CMS simply by looking at all of the colours that are used in the front-end templates, and driving them off a few basic colour variables (which are dictated by the customer’s brand guidelines).


Mixins allow you to group together lots of properties for re-use. The single most useful deployment of mixins is for taking the tedium out of vendor prefixes—rounded corners, for instance:

As you can see, the above mixin will output all of the various vendor-prefixed variables: all I have to write is:

As you can imagine, just those two abilities have saved me huge amounts of time in building websites—and in maintaining them.

Many articles have been written about the power of pre-processors, so I am not going to recreate the user guide here: however, I shall be posting novel or useful Less snippets from time to time.

iTunes-style coverflow

… at least, that is what I have attempted (it’s notoriously difficult). It’s not perfect but the cards do move in 3D space (although the active one is not centred), and they’re controlled by using the check-box hack.

You can navigate through the cards either using the numbers or incredibly—and in a massive affront to all Accessibility practices—by clicking on each card (as usual, there’s no Javascript here at all).

You can view it in fullscreen, or view the code.

Emulating a multi-line ellipsis in CSS

There are various methods for clamping the number of characters, words or lines that can be fitted into a particular space on a website. However, most of them involve limiting the characters either through Javascript or server-side language (and most involve unpleasant Regex expressions).

And while there are a few options for text-overflow , there is currently no elegant cross-browser solution for clamping the number of lines then ending with an ellipsis in CSS.

My personal favourite—because it focuses on the number of lines (which is more important for pernickety designs) rather than words or characters and ends the text excerpt with said ellipsis—is WebKit’s line-clamp property.

Which renders as:

On Webkit browsers, this should be limited to two lines and end in an ellipsis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam non auctor nunc. Aenean porttitor eros quis tellus dapibus vel scelerisque quam laoreet. Fusce vel nulla vitae erat adipiscing feugiat. Nam vitae mauris orci, et congue dolor. Aenean et leo eu dui ullamcorper pretium id at mauris. Donec dolor mauris, dignissim dapibus commodo eget, pretium id lorem. Nullam pharetra mollis imperdiet.

However, this method far from ideal for generating a multi-line ellipsis: it requires all of the attributes above, and is Webkit only—and, even then, it’s a non-standard property. (My theory is that it was created to clamp the information on TV show episodes in the iTunes Store.)

So, Mobify has created an excellent simulation of the line-clamp which will work in most browsers—yes, even in IE (with some tweaking). So, now you can deploy a multi-line ellipsis in CSS…