A blog about code, management, Accessibility and the web in general

Main menu

Category Archives: 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).

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:

Adding data-th to table cells

1

2

3

4

5

6

7

8

9

10

11

12

13

14

<table>

<thead>

<tr>

<th>Name</th>

<td>Job Title</td>

</tr>

</thead>

<tbody>

<tr>

<td data-th="Name">Chris Mounsey</td>

<td data-th="Address">UX Director</td>

</tr>

</tbody>

</table>

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).

CSS

1

2

3

4

5

6

7

8

9

10

11

table th {

display:none;

}

table td {

display:block;

}

table td::before {

content:attr(data-th);

}

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).

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.

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

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

High-level modules should not depend on low-level modules. Both should depend on abstractions.

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!

Conclusions

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.

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.

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.

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 in Less

LESS

1

2

3

4

@nice-blue:#5B83AD;

@light-blue:@nice-blue+#111;

#header {color:@light-blue;}

Output

Variables output

LESS

1

#header {color:#6c94be;}

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

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:

Rounded corners mixin

LESS

1

2

3

4

5

6

7

8

9

.border-radius (@radius: 4px) {

-webkit-border-radius:@radius;

-moz-border-radius:@radius;

-o-border-radius:@radius;

border-radius:@radius;

-moz-background-clip:padding;

-webkit-background-clip:padding-box;

background-clip:padding-box;

}

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

LESS

1

.border-radius();

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.

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.

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.)