A Harder-Working Class

Class is only becoming more important. Focusing on its original definition as an attribute for grouping (or classifying) as well as linking HTML to CSS, recent front-end development practices are emphasizing class as a vessel for structured, modularized style packages. These patterns reduce the need for repetitive declarations that can seriously bloat file sizes, and instil human-readable understanding of how the interface, layout, and aesthetics are constructed.

In the next handful of paragraphs, we will look at how these emerging practices – such as object-oriented CSS and SMACSS – are pushing the relevance of class. We will also explore how HTML and CSS architecture can be further simplified, performance can be boosted, and CSS utility sharpened by combining class with the attribute selector.

A primer on attribute selectors

While attribute selectors were introduced in the CSS 2 spec, they are still considered rather exotic. These well-established and well-supported features give us vastly improved flexibility in targeting elements in CSS, and offer us opportunities for smarter markup. With an attribute selector, you can directly style an element based on any of its unique – or uniquely shared – attributes, without the need for an ID or extra classes. Unlike pseudo-classes, pseudo-elements, and other exciting features of CSS3, attribute selectors do not require any browser-specific syntax or prefix, and are even supported in Internet Explorer 7.

For example, say we want to target all anchor tags on a page that link to our homepage. Where otherwise we might need to manually identify and add classes to the HTML for these specific links, we could simply write:

[href=index.html] {  }

This selector reads: target every element that has an href attribute of “index.html”.

Attribute selectors are more faceted, though, as they also give us some very simple regular expression-like logic that helps further narrow (or widen) a selector’s scope. In our previous example, what if we wanted to also give indicative styles to any anchor tag linking to an external site? With no way to know what the exact href value would be for every external link, we need to use an expression to match a common aspect of those links. In this case, we know that all external links need to start with “http”, so we can use that as a hook:

[href^=http] {  }

The selector here reads: target every element that has an href attribute that begins with “http” (which will also include “https”). The ^= means “starts with”. There are a few other simple expressions that give us a lot of flexibility in targeting elements, and I have found that a deep understanding of these and other selector types to be very useful.

The class-attribute selector

By matching classes with the attribute selector, CSS can be pushed to accomplish some exciting new feats. What I call a class-attribute selector combines the advantages of classes with attribute selectors by targeting the class attribute, rather than a specific class. Instead of selecting .urgent, you could select [class*=urgent]. The latter may seem like a more verbose way of accomplishing the former, but each would actually match two subtly different groups of elements.

Eric Meyer first explored the possibility of using classes with attribute selectors over a decade ago. While his interest in this technique mostly explored the different facets of the syntax, I have found that using class-attribute selectors can have distinct advantages over either using an attribute selector or a straightforward class selector.

First, let’s explore some of the subtleties of why we would target class before other attributes:

  • Classes are ubiquitous. They have been supported since the HTML 4 spec was released in 1999. Newer attributes, such as the custom data attribute, have only recently begun to be adopted by browsers.
  • Classes have multiple ways of being targeted. You can use the class selector or attribute selector (.classname or [class=classname]), allowing more flexible specificity than resorting to an ID or !important.
  • Classes are already widely used, so adding more classes will usually require less markup than adding more attributes.
  • Classes were designed to abstractly group and specify elements, making them the most appropriate attribute for styling using object-oriented methods (as we will learn in a moment).

Also, as Meyer pointed out, we can use the class-attribute selector to be more strict about class declarations. Of these two elements:

<h2 class="very urgent">
<h2 class="urgent">

…only the second h2 would be selected by [class=urgent], while .urgent would select both. The use of = matches any element with the exact class value of “urgent”. Eric explores these nuances further in his series on attribute selectors, but perhaps more dramatic is the added power that class-attribute selectors can bring to our CSS.

More object-oriented, more scalable and modular

Nicole Sullivan has been pushing abstracted, object-oriented thinking in CSS development for years now. She has shared stacks of knowledge on how behemoth sites have seen impressive gains in maintenance overhead and CSS file sizes by leaning heavier on classes derived from common patterns. Jonathan Snook also speaks, writes and is genuinely passionate about improving our markup by using more stratified and modular class name conventions. With SMACSS, he shows this to be highly useful across sites – both complex and simple – that exhibit repeated design patterns. Sullivan and Snook both push the use of class for styling over other attributes, and many front-end developers are fast advocating such thinking as best practice.

With class-attribute selectors, we can further abstract our CSS, pushing its scalability. In his chapter on modules, Snook gives the example of a .pod class that might represent a certain set of styles. A .pod style set might be used in varying contexts, leading to CSS that might normally look like this:

.pod {  }
form .pod {  }
aside .pod {  }

According to Snook, we can make these styles more portable by targeting more verbose classes, rather than context:

.pod {  }
.pod-form {  }
.pod-sidebar {  }

…resulting in the following HTML:

<div class="pod">
<div class="pod pod-form">
<div class="pod pod-sidebar">

This divorces the <div>’s styles from its context, making it applicable to any situation in which it is needed. The markup is clean and portable, and the classes are imbued with meaning as to what module they belong to.

Using class-attribute selectors, we can simplify this further:

[class*=pod] {  }
.pod-form {  }
.pod-sidebar {  }

The *= tells the browser to look for any element with a class attribute containing “pod”, so it matches “pod”, “pod-form”, “pod-sidebar”, etc. This allows only one class per element, resulting in simpler HTML:

<div class="pod">
<div class="pod-form">
<div class="pod-sidebar">

We could further abstract the concept of “form” and “sidebar” adjustments if we knew that each of those alterations would always need the same treatment.

/* Modules */
[class*=pod] {  }
[class*=btn] {  }

/* Alterations */
[class*=-form] {  }
[class*=-sidebar] {  }

In this case, all elements with classes appended “-form” or “-sidebar” would be altered in the same manner, allowing the markup to stay simple:

<form>
  <h2 class="pod-form">
  <a class="btn-form" href="#">

<aside>
  <h2 class="pod-sidebar">
  <a class="btn-sidebar" href="#">

50+ shades of specificity

Classes are just powerful enough to override element selectors and default styling, but still leave room to be trumped by IDs and !important styles. This makes them more suitable for object-oriented patterns and helps avoid messy specificity issues that can not only be a pain for developers to maintain, but can also affect a site’s performance. As Sullivan notes, “In almost every case, classes work well and have fewer unintended consequences than either IDs or element selectors”. Proper use of specificity and cascade is crucial in building straightforward, efficient CSS.

One interesting aspect of attribute selectors is that they can be compounded for increasing levels of specificity. Attribute selectors are assigned a specificity level of ten, the same as class selectors, but both class and attribute selectors can be chained together, giving them more and more specificity with each link. Some examples:

.box {  } 
/* Specificity of 10 */

.box.promo {  } 
/* Specificity of 20 */

[class*=box] {  } 
/* Specificity of 10 */

[class*=box][class*=promo] {  } 
/* Specificity of 20 */

You can chain both types together, too:

.box[class*=promo] {  } 
/* Specificity of 20 */

I was amused to find, though, that you can chain the exact same class and attribute selectors for infinite levels of specificity

.box {  } 
/* Specificity of 10 */

.box.box {  } 
/* Specificity of 20 */

.box.box.box {  } 
/* Specificity of 30 */

[class*=box] {  }
/* Specificity of 10 */

[class*=box][class*=box] {  }
/* Specificity of 20 */

[class*=box][class*=box][class*=box] {  }
/* Specificity of 30 */

.box[class*=box].box[class*=box] {  } 
/* Specificity of 40 */

To override .box styles for promo, we wouldn’t need to add an ID, change the order of .promo and .box in the CSS, or resort to an !important style. Granted, any issue that might need this fine level of specificity tweaking could probably be better solved with clever cascades, but having options never hurts.

Smarter CSS

One of the most powerful aspects of the class-attribute selector is its ability to expand the simple logic found in CSS. When developing Gridset (an online tool for building grids and outputting them as CSS), I realized that with the right class name conventions, class-attribute selectors would allow the CSS to be smart enough to automatically adjust for column offsets without the need for extra classes. This imbued the CSS output with logic that other frameworks lacked, and makes a developer’s job much easier.

Say you need an element that spans column five (c5) to column six (c6) on your grid, and is preceded by an element spanning column one (c1) to column three (c3). The CSS can anticipate such a scenario:

.c1-c3 + .c5-c6 {
  margin-left: 25%; /* …or the width of column four plus two gutter widths */
}

…but to accommodate all of the margin offsets that could span that same gap, we would need to write a rather protracted list for just a six column grid:

.c1-c3 + .c5-c6,
.c1-c3 + .c5,
.c2-c3 + .c5-c6,
.c2-c3 + .c5,
.c3 + .c5-c6,
.c3 + .c5 {
  margin-left: 25%; 
}

Now imagine how the verbosity compounds when we repeat this type of declaration for every possible margin in a grid. The more columns added to the grid, the longer this selector list would get, too, making the CSS harder for the developer to maintain and slowing the load time. Using class-attribute selectors, though, this can be much simpler:

[class*=c3] + [class*=c5] {
  margin-left: 25%;
}

I’ve detailed how we extract as much logic as possible from as little CSS as needed on the Gridset blog.

More flexible selectors

In a recent project, I was working with Drupal-generated classes to change styles for certain special pages on a site. Without being able to change the code base, I was left trying to find some specific aspect of the generated HTML to target. I noticed that every special page was given a prefixed class, unique to the page, resulting in CSS like this:

.specialpage-about,
.specialpage-contact,
.specialpage-info,
…

…and the list kept growing with each new special page. Such bloat would lead to problems down the line, and add development overhead to editorial decisions, which was a situation we were trying to avoid. I was easily able to fix this, though, with a concise class-attribute selector:

[class*=specialpage-]

The CSS was now flexible enough to accommodate both the editorial needs of the client, and the development restrictions of the CMS.

Selector performance

As Snook tells us in his chapter on Selector Performance, selectors are read by the browser from right to left, matching every element that adheres to each rule (or part of the selector). The more specific we can make the right-most rules – and every other part of your selectors – the more performant your CSS will be. So this selector:

.home-page .promo .main-header

…would be more performant than:

.home-page div header

…because there are likely many more header and div elements on the page, but not so many elements with those specific classes.

Now, the class-attribute selector could be more general than a class selector, but not by much. I ran numerous tests based on the work of Steve Souders (and a few others) to test a class-attribute selector against a normal class selector. Given that Javascript will freeze during style rendering, I created a script that will add, then remove, a stylesheet on a page 5000 times, and measure only the time that elapses during the rendering freeze. The script runs four tests, essentially: one where a class selector and class-attribute Selector match a single element, and one they match multiple elements on the page.

After running the test over 100 times and averaging the results, I have not seen a significant difference in rendering times. (As of this writing, the class-attribute selector has been 0.398% slower on average.) View the results here.

Given the sheer amount of bytes potentially saved by reducing selector lists, though, I am confident class-attribute selectors could shorten load times on larger sites and, at the very least, save precious development time.

Conclusion

With its flexibility and broad remit, class has at times been derided as too lenient, allowing CMSes and lazy developers to fill its values with presentational hacks or verbose gibberish. There have even been calls for an early retirement. Class continues, though, to be one of our most crucial tools.

Front-end developers are rightfully eager to expand production abilities through innovations such as Sass or LESS, but this should not preclude us from honing the tools we already know as well. Every technique demonstrated in this article was achievable over a decade ago and most of the same thinking could be applied to IDs, rels, or any other attribute (though the reasons listed above give class an edge). The recent advent of methods such as object-oriented CSS and SMACSS shows there is still much room left to expand what simple HTML and CSS can accomplish. Progress may not always be found in the innovation of our tools, but through sharpening our understanding of them.

About the author

Nathan Ford is Creative Director at Mark Boulton Design where he helps a small, talented team of designers build beautiful experiences for a queue of clients such as Al Jazeera, ESPN, and CERN. He is also lead developer on Gridset, an online tool for building grid systems. Read more of his infrequent writing on his blog, Art=Work, where he shares thoughts and tools to make working on the web a bit easier (hopefully), or follow @nathan_ford on Twitter.

More articles by Nathan

Comments