Menu Search
Jump to the content X X
Smashing Conf Barcelona 2016

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Semantic CSS With Intelligent Selectors

“Form ever follows function. This is the law.” So said the architect and “father of skyscrapers” Louis Sullivan1. For architects not wishing to crush hundreds of innocent people under the weight of a colossal building, this rule of thumb is pretty good. In design, you should always lead with function, and allow form to emerge as a result. If you were to lead with form, making your skyscraper look pretty would be easier, but at the cost of producing something pretty dangerous.

So much for architects. What about front-end architects — or “not real architects,” as we are sometimes known? Do we abide by this law or do we flout it?

With the advent of object-oriented CSS2 (OOCSS), it has become increasingly fashionable to “decouple presentation semantics from document semantics3.” By leveraging the undesignated meanings of classes4, it is possible to manage one’s document and the appearance of one’s document as curiously separate concerns.

Overthinking how a functional thing should look.

In this article, we will explore an alternative approach to styling Web documents, one that marries document semantics to visual design wherever possible. With the use of “intelligent” selectors, we’ll cover how to query the extant, functional nature of semantic HTML in such a way as to reward well-formed markup. If you code it right, you’ll get the design you were hoping for.

If you are like me and have trouble doing or thinking about more than one thing at a time, I hope that employing some of these ideas will make your workflow simpler and more transferable between projects. In addition, the final section will cover a more reactive strategy: We’ll make a CSS bookmarklet that contains intelligent attribute selectors to test for bad HTML and report errors using pseudo-content.

Intelligent Selectors Link

With the invention of style sheets came the possibility of physically separating document code from the code used to make the document presentable. This didn’t help us to write better, more standards-aware HTML any more than the advent of the remote control resulted in better television programming. It just made things more convenient. By being able to style multiple elements with a single selector (p for paragraphs, for instance), consistency and maintenance became significantly less daunting prospects.

television remote reading DRIVEL

The p selector is an example of an intelligent selector in its simplest form. The p selector is intelligent because it has innate knowledge of semantic classification. Without intervention by the author, it already knows how to identify paragraphs and when to style them as such — simple yet effective, especially when you think of all of the automatically generated paragraphs produced by WYSIWYG editors.

So, if that’s an intelligent selector, what’s an unintelligent one? Any selector that requires the author to intervene and alter the document simply to elicit a stylistic nuance is an unintelligent selector. The class is a classic unintelligent selector because it is not naturally occurring as part of semantic convention. You can name and organize classes sensibly, but only with deliberation; they aren’t smart enough to take care of themselves, and browsers aren’t smart enough to take care of them for you.

Unintelligent selectors are time-intensive because they require styling hooks to be duplicated case by case. If we didn’t have p tags, we’d have to use unintelligent selectors to manufacture paragraphs, perhaps using .paragraph in each case. One of the downsides of this is that the CSS isn’t portable — that is, you can’t apply it to an HTML document without first going through the document and adding the classes everywhere they are required.

class selector called paragraph

Unintelligent selectors at times seem necessary, or at least easier, and few of us are willing to rely entirely on intelligent selectors. However, some unintelligent selectors can become “plain stupid” selectors by creating a mismatch between document structure and presentation. I’ll be talking about the alarming frequency with which the unintelligent .button selector quickly becomes plain stupid.

Vive la Différence Link

Intelligent selectors are not confined just to the basic elements offered to us in HTML’s specification. To build complex intelligent selectors, you can defer to combinations of context and functional attribution to differentiate basic elements. Some elements, such as <a>, have a multitude of functional differences to consider and exploit. Other elements, such as <p>, rarely differ in explicit function but assume slightly different roles according to context.

header p {
   /* styles for prologic paragraphs */

footer p {
   /* styles for epilogic paragraphs */

Simple descendent selectors like these are extremely powerful because they enable us to visually disclose different types of the same element without having to physically alter the underlying document. This is the whole reason why style sheets were invented: to facilitate physical separation without breaking the conceptual reciprocity that should exist between document and design.

a semantic heirarchy of needs: what it is, how it functions, where it is5

Inevitably, some adherents of OOCSS treat the descendent selector with some suspicion6, with the more zealous insisting on markup such as the example below, found in BEM’s “Definitions7” documentation.

<ul class="menu">
  <li class="menu__item">…</li>
  <li class="menu__item">…</li>

I won’t cover contextual selectors any further because, unless you have a predilection for the kind of overprescription outlined above, I’m sure you already use them every day. Instead, we’ll concentrate on differentiation by function, as described in attributes and by attribute selectors.

Even those who advocate for conceptual separation between CSS and HTML are happy to concede that some attributes — most attributes besides classes and custom data attributes, in fact — have an important bearing on the internal functioning of the document. Without href, your link won’t link to anything. Without type, the browser won’t know what sort of input to render. Without title, your abbr could be referring to either the British National Party or Banco Nacional de Panama.

Some of these attributes may improve the semantic detail of your document, while others are needed to ensure the correct rendering and functioning of their subject elements. If they’re not there, they should be, and if they are there, why not make use of them? You can’t write CSS without writing HTML.

The rel Attribute Link

The rel attribute emerged as a standard for link relations8, a method of describing some specific purpose of a link. Not all links, you see, are functionally alike. Thanks to WordPress’ championing, rel="prev" and rel="next" are two of the most widely adopted values, helping to describe the relationship between individual pages of paginated blog content. Semantically, an a tag with a rel attribute is still an a tag, but we are able to be more specific. Unlike with classes, this specificity is semantically consequential.

The rel attribute should be used where appropriate because it is vindicated by HTML’s functional specification9 and can therefore be adopted by various user agents to enhance the experience of users and the accuracy of search engines. How, then, do you go about styling such links? With simple attribute selectors, of course:

[rel="prev"] {
  /* styling for "previous links" */

[rel="next"] {
  /* styling for "next" links */

Attribute selectors like these are supported by all but the most archaic, clockwork browsers, so that’s no reason not to use them anywhere the attributes exist. In terms of specificity, they have the same weight as classes. No woe there either, then. However, I recall it being suggested that we should decouple document and presentation semantics. I don’t want to lose the rel attributes (Google has implemented them10, for one thing), so I’d better put an attribute that means nothing on there as well and style the element via that.

  <a href="/previous-article-snippet/" rel="prev" class="prev">previous page</a>

The first thing to note here is that the only part of the element above that does not contribute to the document’s semantics is the class. The class, in other words, is the only thing in the document that has nothing functionally to do with it. In practice, this means that the class is the only thing that breaks with the very law of separation that it was employed to honor: It has a physical presence in the document without contributing to the document’s structure.

OK, so much for abstraction, but what about maintenance? Accepting that we’ve used the class as our styling hook, let’s now examine what happens when some editing or refactoring has led us to remove some attributes. Suppose we’ve used some pseudo-content to place a left-pointing arrow before the [rel="prev"] link’s text:

.prev:before {
  content: '2190'; /* encoding for a left-pointing arrow ("←") */

previous link with arrow

Removing the class will remove the pseudo-content, which in turn will remove the arrow (obviously). But without the arrow, nothing remains to elucidate the link’s extant prev relationship. By the same token, removing the rel attribute will leave the arrow intact: The class will continue to manage presentation, all the time disguising the nonexistence of a stated relationship in the document. Only by applying the style directly, via the semantic attribute that elicits it, can you keep your code and yourself honest and accurate. Only if it’s really there, as a function of the document, should you see it.

Attribute Substrings Link

I can imagine what you’re thinking: “That’s cute, but how many instances are there really for semantic styling hooks like these on hyperlinks? I’m going to have to rely on classes at some point.” I dispute that. Consider this incomplete list of functionally disimilar hyperlinks, all using the a element as their base:

  • links to external resources,
  • links to secure pages,
  • links to author pages,
  • links to help pages,
  • links to previous pages (see example above),
  • links to next pages (see example above again),
  • links to PDF resources,
  • links to documents,
  • links to ZIP folders,
  • links to executables,
  • links to internal page fragments,
  • links that are really buttons (more on these later),
  • links that are really buttons and are toggle-able,
  • links that open mail clients,
  • links that cue up telephone numbers on smartphones,
  • links to the source view of pages,
  • links that open new tabs and windows,
  • links to JavaScript and JSON files,
  • links to RSS feeds and XML files.

That’s a lot of functional diversity, all of which is understood by user agents of all sorts. Now consider that in order for all of these specific link types to function differently, they must have mutually differential attribution. That is, in order to function differently, they must be written differently; and if they’re written differently, they can be styled differently.

In preparing this article, I created a proof of concept, named Auticons11. Auticons is an icon font12 and CSS set that styles links automatically. All of the selectors in the CSS file are attribute selectors that invoke styles on well-formed hyperlinks, without the intervention of classes.


In many cases, Auticons queries a subset of the href value in order to determine the function of the hyperlink. Styling elements according to the way their attribute values begin or end or according to what substring they contain throughout the value is possible. Below are some common examples.

The Secure Protocol Link

Every well-formed (i.e. absolute) URL begins with a URI scheme14 followed by a colon. The most common on the Web is http:, but mailto: (for SMTP) and tel: (which refers to telephone numbers) are also prevalent. If we know how the href value of the hyperlink is expected to begin, we can exploit this semantic convention as a styling hook. In the following example for secure pages, we use the ^= comparator, which means “begins with.”

a[href^="https:"] {
   /* style properties exclusive to secure pages */

a link to a secure page with a lock icon

In Auticons, links to secure pages become adorned with a padlock icon according to a specific semantic pattern, identifiable within the href attribute. The advantages of this are as follows:

  • Links to secure pages — and only secure pages — are able to resemble links to secure pages by way of the padlock icon.
  • Links to secure pages that cease to be true links to secure pages will lose the https protocol and, with it, the resemblance.
  • New secure pages will adopt the padlock icon and resemble links to secure pages automatically.

This selector becomes truly intelligent when applied to dynamic content. Because secure links exist as secure links even in the abstract, the attribute selector can anticipate their invocation: As soon as an editor publishes some content that contains a secure link, the link resembles a secure one to the user. No knowledge of class names or complex HTML editing is required, so even simple Markdown15 will create the style:

[Link to secure page](

Note that using the [href^="https:"] prefix is not infallible because not all HTTPS pages are truly secure. Nonetheless, it is only as fallible as the browser itself. Major browsers all render a padlock icon natively in the address bar when displaying HTTPS pages.

PayPal secure page

File Types Link

As promised, you can also style hyperlinks according to how their href value ends. In practice, this means you can use CSS to indicate what type of file the link refers to. Auticons supports .txt, .pdf, .doc, .exe and many others. Here is the .zip example, which determines what the href ends with, using $=:

[href$=".gz"]:before {
   content: 'E004'; /* unicode for the zip folder icon */

Combinations Link

You know how you can get all object-oriented and use a selection of multiple classes on elements to build up styles? Well, you can do that automatically with attribute selectors, too. Let’s compare:

/* The CSS for the class approach */

.new-window-icon:after {
   content: '[new window icon]';

.twitter-icon:before {
  content: '[twitter icon]';

/* The CSS for the attribute selector approach */

[target="_blank"]:after {
   content: '[new window icon]';

[href*=""]:before {
  content: '[twitter icon]';

(Note the *= comparator, which means “contains.” If the value string contains the substring, then the style will be honored.)

<!-- The HTML for the class approach -->

<a href="" target="_blank" class="new-window-icon twitter-icon">@heydonworks</a>

<!-- The HTML for the attribute selector approach -->

<a href="" target="_blank">@heydonworks</a>

A twitter link with icons to show that it goes to twitter and is external

Any content editor charged with adding a link to a Twitter page now needs to know only two things: the URL (they probably know the Twitter account already) and how to open links in new tabs (obtainable from a quick Google search).

Inheritance Link

Some unfinished business: What if we have a link that does not match any of our special attribute selectors? What if a hyperlink is just a plain old hyperlink? The selector is an easy one to remember, and performance fanatics will be pleased to hear that it couldn’t be any terser without existing at all.

A basic anchor selector (a)

Flippancy aside, let me assure you that inheritance within the cascade works with attribute selectors just as it does with classes. First, style your basic a — perhaps with a text-decoration: underline rule to keep things accessible; then, progressively enhance further down the style sheet, using the attribute selectors at your disposal. Browsers such as Internet Explorer (IE) 7 do not support pseudo-content at all. Thanks to inheritance, at least the links will still look like links.

a {
  color: blue;
  text-decoration: underline;

a[rel="external"]:after {
   content: '[icon for external links]';

Actual Buttons Are Actual Link

In the following section, we’ll detail the construction of our CSS bookmarklet for reporting code errors. Before doing this, let’s look at how plain stupid selectors can creep into our workflow in the first place.

Adherents of OOCSS are keen on classes because they can be reused, as components. Hence, .button is preferable to #button. I can think of one better component selector for button styles, though. Its name is easy to remember, too.

button element selector

The <button> element represents a button.

W3C Wiki16

Topcoat17 is an OOCSS BEM-based UI framework from Adobe. The CSS for Topcoat’s various button styles is more than 450 lines if you include the comment blocks. Each of these comment blocks suggests applying your button style in a manner similar to this introductory example:

   <a class="topcoat-button">Button</a>

This example is not a button. No, sir. If it were a button, it would be marked up using <button>. In fact, in every single browser known to man, if it were marked up as a button and no author CSS was supplied, you could count on it looking like a button by default. It’s not, though; it’s marked up using <a>, which makes it a hyperlink — a hyperlink, in fact, that lacks an href, meaning it isn’t even a hyperlink. Technically, it’s just a placeholder18 for a hyperlink that you haven’t finished writing yet.

Dog in a shark costume
A dog in a shark costume does not a shark make. (Image: reader of the pack19)

The examples in Topcoat’s CSS are only examples, but the premise that the class defines the element and not the HTML is deceptive. No amount of class name modification via “meaningful hyphenation” can make up for this invitation to turn your unintelligent selector into a plain stupid one and to just code stuff wrong.

Update: Since writing this article, has replaced these examples with <button> examples. This is great! However, I still have my reservations about the way the examples expound the use of the .is-disabled class while omitting the proper disabled attribute. To hear both sides, find my conversation with the Topcoat representative in the comments. For further examples of OOCSS-facilitated web standards mishaps, look no further than semantic-ui.com20. The “standard button” in their examples is a <div> containing an empty <i>.

See No Evil, Hear No Evil Link

“If it looks like a duck, swims like a duck, and quacks like a duck, then it probably is a duck.”

A link that resembles a button and triggers button-like JavaScript events is, to many, a button. However, this only means that it has passed the first two stages of the “duck test.” For all users to be able to apply inductive reasoning and discern the button as such, it must also quack like one. Because it remains a link, it will be announced by screen readers as “link,” meaning that your allegorical skyscraper is not wheelchair-accessible. Avoiding this kind of unnecessary confusion for assistive technology users is not a pursuit of semantic perfection but a responsibility we should undertake for real benefit.

Nonetheless, some will insist on using a as the basis of their buttons. Hyperlinks are (slightly) easier to restyle consistently, after all. If a is the element of choice, then there is only one way to make it a close-to-true button in the accessibility layer. You guessed it: You must apply another meaningful attribute in the form of a WAI ARIA21 role. To ensure that a hyperlink element looks like a button for good reason, apply only the following attribute selector.

[role="button"] {
   /* semantic CSS for modified elements that are announced as “button” in assistive technologies */

Quality Assurance With Attribute Selectors Link

“CSS gives so much power to the class attribute, that authors could conceivably design their own “document language” based on elements with almost no associated presentation (such as DIV and SPAN in HTML) and assigning style information through the “class” attribute. Authors should avoid this practice since the structural elements of a document language often have recognized and accepted meanings.”

– “Selectors22,” CSS Level 2, W3C

The reason we have two elements — a and button — is to semantically demarcate two entirely different types of functional interaction. While the hyperlink denotes a means to go somewhere, the button is intended as the instigator of an event or action. One is about traversal, the other about transformation. One facilitates disengagement, the other engagement.

To make sure we don’t do anything too daft and get our links and buttons muddled up, we will now build a CSS bookmarklet that uses intelligent attribute selectors to test the validity and quality of the two respective elements.

Inspired partly by Eric Meyer’s post23 and taking a few cues from DiagnostiCSS24, this style sheet will combine attribute selectors and the :not selector (or negation pseudo-class25) to highlight problems in the HTML. Unlike these other two implementations, it will write an error to the screen using pseudo-content. Each error will be written in Comic Sans against a pink background.

By connecting function directly to form, we see that ugly markup results in ugly CSS. Consider this the revenge of an abused document, exacted on its designer. To try it out, drag revenge.css to your bookmarks, and click the bookmark to trigger it on any page that you fancy. Note: It won’t currently work for pages that are served over https.

Drag to your bookmarks bar.

Rule 1 Link

“If it’s a hyperlink, it should have an href attribute.”

a:not([href]):after {
   content: 'Do you mean for this to be a link or a button, because it does not link to anything!';
   display: block !important;
   background: pink !important;
   padding: 0.5em !important;
   font-family: 'comic sans ms', cursive !important;
   color: #000 !important;
   font-size: 16px !important;

Notes: In this example, we are testing not the attribute’s value, but whether the attribute exists in the first place — that is, whether [href] matches any element with an href attribute. This test is only appropriate on hyperlinks, hence the a prefix. The rule reads like, “For every a element that is not also an [href] element, append some pseudo-content with an error notice.”

Rule 2 Link

“If it’s a hyperlink and has an href attribute, it should have a valid value.”

a[href=""]:after, a[href$="#"]:after, a[href^="javascript"]:after {
   content: 'Do you mean for this link to be a button, because it does not go anywhere!';
   /*... ugly styles ...*/

Notes: If the href is empty, ends in a # or is using JavaScript, it’s probably being used as a button without the correct button element. Note that I am using “starts with javascript.” Standard practice for voiding hrefs is to use javascript:void(0), but we can’t depend on that always being written in the same way (with or without a space after the colon, for example).

Rule 3 Link

“If it uses a button class, it should be a button — at least in the accessibility layer.”

a[class*="button"]:not([role="button"]):after {
   content: 'If you are going to make it look like a button, make it a button, damn it!';
   /*... ugly styles ...*/

Notes: In this example, we’re demonstrating how you can chain negation when testing for attributes. Each selector reads like this: “If the element has a class that says it’s a button but it’s not a button element and it doesn’t have the correct role to make it a button in the accessibility layer and it’s not an input being used as a button, then… well, you’re lying.” I’ve had to use [class*="button"] to catch the many Topcoat class variations (62 in total!) that fail to enforce actual buttons on hyperlinks. I’ve noticed that some authors use button-container and the like on parent elements, which is why the a qualifier is included to avoid false positives. You may recognize the .btn class from Twitter Bootstrap, which (if you’ve read the component’s documentation27 carefully) you’ll know is also unsure about whether links or buttons are buttons.

Rule 4 Link

“If it is an a element with role="button", then it should link to somewhere when JavaScript is off.”

a[role="button"]:not([href*="/"]):not([href*="."]):not([href*="?"]):after {
   content: 'Either use a link fallback, or just use a button element.';
   /*... ugly styles ...*/

Notes: We can be fairly sure that hrefs that do not include one of /, . (usually to precede a file extension) or ? (to start a query string) are probably bogus. Getting links to act as buttons and return: false when JavaScript is on is fine — fine, that is, if they have a page to go to when JavaScript is off. In fact, it’s the only legitimate reason I can think of not to use <button> instead.

Rule 5 Link

“You can’t disable a hyperlink.”

a[class*="button"][class*="disabled"]:after {
   content: 'You cannot disable a hyperlink. Use a button element with disabled="disabled".';
   /*... ugly styles ...*/

Notes: Even ancient user agents understand the disabled attribute, so use it with an appropriate element in a compliant way. You can concatenate attribute selectors just as you can concatenate classes: In the last of the three selectors, we’re saying, “If it’s a link that contains the substring button and the substring disabled, then print an error message.” Twitter Bootstrap uses the second form, .btn.disabled, in its style sheet, but not with the a prefix. We’ll only consider it an error if used on hyperlinks.

Rule 6 Link

“Buttons in forms should have explicit types.”

form button:not([type]):after {
    content: 'Is this a submit button, a reset button or what? Use type="submit", type="reset" or type="button"';

Notes: We need to determine whether buttons within forms have explicit types, because some browsers28 will treat any button in this context without a specified type as type="submit". We want to be absolutely sure that the form won’t submit if our button has a different purpose.

Rule 7 Link

“Both hyperlinks and buttons should have some sort of content or an ARIA label.”

button:not([aria-label]):not([aria-labelledby]) img:only-child:not([alt]):after,
a:not([aria-label]):not([aria-labelledby]) img:only-child:not([alt]):after {
   content: 'All buttons and links should have text content, an image with alt text or an ARIA label';
   /*... ugly styles ...*/

Notes: Buttons and links that don’t include any kind of direction for their usage — in either textual or graphical form — are pretty bogus. These final two selectors are perhaps the most complex I’ve ever written. For the hyperlink version, the selector reads something like this: “If it is a hyperlink that does not have either an aria-label attribute or an aria-labelledby attribute and it contains only an image as content but this image does not have an alt attribute, then write the ugly error message.” Also, note the use of the :empty selector29. Arguably, no element that is not self-closing should ever be left empty.

Ten points to the first person using revenge.css who can tell me where I’ve broken my own rule in this very article. Trust me, the error is definitely there.

Conclusion Link

The reason I use the kinds of selectors and patterns described above is not to try something different or to have something new to write about. Attribute selectors aren’t, by themselves, anything new anyway. IE 6 is the only browser30 that doesn’t support them. The reason I use them is because I simply do not have the time or mental capacity to “do” HTML and CSS in parallel. My brain just isn’t good enough for that. The reason I style my page headers with [role="banner"] and not .page-header is because that’s the only way I’ll know — upon seeing the intended visual effect — that I’ve put the navigable landmark31 in place. How else does one keep track? You can’t just leave it to testing, because then it’s usually too late.

There’s no such thing as semantic CSS. There’s only semantic HTML and its visible form. In this article I have tried to demonstrate that, by coupling the function and form of Web pages directly, you can create mechanisms for reward and punishment. On the one hand, you can set up selectors that invoke visual motifs only when the suitable markup is used. On the other hand, you can query the markup for bad patterns and erode the visual design as a commitment to the underlying ugly truth.

It’s true that not all the styling hooks in your arsenal will likely ever be uniformly semantic or intelligent. Classes are often desirable as polyfills for much needed elements or attributes that have yet to be standardized. That’s how .footer became <footer> and type="text" (with a bunch of JavaScript) became type="url". Other times, they are helpful for doing non-semantic layout scaffolding with grid frameworks32 and the like.

However, if you are committed to giving CSS its own completely separate logic, then you are bound to create unnecessary arguments between form and function. In this eventuality, only constant vigilance can protect against inaccessibility and invalidity. To make matters worse, trying to manufacture pseudo-semantics purely with classes makes it easy to fall into one of those interminable discussions over what makes a semantic class name33. You’ll start spending less time using the remote to control the TV and more time just sitting there, contemplating the remote control held in your hand.

Life is too short.


Footnotes Link

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
SmashingConf Barcelona 2016

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook


Heydon is a UX designer and writer interested in web application accessibility and intelligent layout systems. He gesticulates a lot and is terrible at computer games. His acclaimed book on accessibility has been published with Smashing Magazine.

  1. 1

    Jens Grochtdreis

    August 20, 2013 3:21 am

    Thanks a lot for this massive and really good article. I published myself an article today in my German blog about this topic, although not that detailed.

    Your examples are really good and point to the shortcomings of all the object-oriented concepts. The BEM example always makes me shiver. Not long ago I marked navigations with list-items that hold the same class as a bad example in my lectures. Nowadays it is recommended as best practice? Not in my book!

    But I wouldn’t go so far as to ban all classes from my document. Classes have their use in identifying the constructing modules of my page. If necessary even he elements of those modules can have classes. But mostly they can be targeted with selectors.

    And hopefully many people will read this article to identify over-classification of HTML as a way of doing it wrong.

    • 2

      Heydon Pickering

      August 20, 2013 3:57 am

      Sounds good, Jens.

      Regrettably, my German is very poor.

      Can we have a link for our Freiburg friends, though?


    • 3

      James Nicholls

      August 21, 2013 12:41 am

      I believe one of the reasons for using name-spaced classes for elements within modules is to avoid styles from other libraries/devs leaking into your module. How would you propose to avoid this situation? Would you just avoid 3rd-party libraries and enforce rigorous standards within your development team?

      • 4

        Heydon Pickering

        August 21, 2013 1:15 am


        I’m often asked what styling hook I’ve designated for buttons, for instance. The conversation goes a bit like this:

        DEV: “What are we using for button styles again? Is it just ‘button’?”
        ME: “Well, you know me…”
        DEV: “Okay… I’ll just use ‘button'”
        DEV: “There – class=’button’. Simple.”
        ME: “What??”
        DEV: “Ha ha. Only joking. I put a button element in.”

        Recently, when I’ve been writing the CSS and someone else is writing the HTML, they know to use the correct elements and roles because they know that’s all I’ve catered for in my normalization file. Classes don’t do a lot in my CSS :-)

        • 5

          James Nicholls

          August 21, 2013 1:22 am

          Fair enough :). Theoretically I agree with your approach but I’m concerned about maintainability. I’d have to see how it works on a big project.

        • 6

          The story about you and the dev is so funny…

  2. 7

    Excellent article. I appreciate the mention of Topcoat as well. Unfortunately your info is out of date. We use a button tag because well, it’s a button. This was not included previously since we were iterating on getting the markup right ( portable, accessible, minimal ) and were lazer focused on CSS performance, which is something you don’t mention in this article. Most of the selectors you outline suffer from the lack of direct specificity which is the largest contributing factor to CSS selector speed. CSS selector speed is a very minor part of page performance, but if you are making an application where feel matters you most likely will need to consider how these factors are compounded at some point. With every decision you make there will always be trade-offs. The example of using an anchor tag as a button is a great example. This tag has a special ability in that it can trigger navigation. Using a button tag as a button sounds almost humorously straight forward, but if all that button does is trigger navigation then you are replicating built in functionalty with your own script. This starts to uncover what Topcoat is trying to address; The web is a platform that is expressing far more than just documents. Applications built on this platform need to take special considerations since the web has evolved to support a use that was not even imagined at it’s inception. To me it seems that every mention of semantics on the web eventually devolves into a pedantic debate fueled by zealots who believe that there can only be one right answer. I feel that we should instead consider our users and make our decisions based off of what fulfills their needs best.

    • 8

      Heydon Pickering

      August 20, 2013 5:28 am

      Hey, thanks for the detailed comment. Sorry to demonize Topcoat; it’s certainly no worse than other frameworks in this respect.

      I’ve just downloaded version 0.6.0 and am pleased to share that the link examples have been replaced with buttons. Thanks!

      I am still, however, concerned with the below

      <button class="topcoat-button is-disabled">Button</button>

      since it implies that using the “is-disabled” class suffices. No disabled="disabled" (or readonly attribute) is included. Some developers might not be aware that these are required to make the button a proper disabled button and “is disabled” a true statement. One could test for this with something like:

      button[class*="disabled"]:not([disabled]):after {
      content: 'Use disabled="disabled" to disable this button';

      “The example of using an anchor tag as a button is a great example. This tag has a special ability in that it can trigger navigation. Using a button tag as a button sounds almost humorously straight forward, but if all that button does is trigger navigation then you are replicating built in functionalty with your own script.”

      Yeah, then I’d use a link :-)

      “Most of the selectors you outline suffer from the lack of direct specificity which is the largest contributing factor to CSS selector speed. CSS selector speed is a very minor part of page performance, but if you are making an application where feel matters you most likely will need to consider how these factors are compounded at some point.”

      Agreed, CSS selector performance is a very minor part of page performance. In most cases, just compressing or removing a couple of images would have a much greater impact. However, I do appreciate that a lot of dynamic CSS – especially using animations – might require a selector audit.

      “The web is a platform that is expressing far more than just documents. Applications built on this platform need to take special considerations”

      Again, I agree, which is partly why I wrote this. By its very nature, a “one page app” is not (for the most part) a linked document. I wanted to create awareness around the button as a more appropriate “clickable” in such a context.

  3. 9

    The author has written a couple of thousand words on using attribute selectors instead of classes.

    I’m not saying he’s wrong, but the article could have been more concise and (a lot) less condescending.

  4. 10

    The danger you run into with this is assuming that every button, or link, or address should be styled the same way. On some sites, with a lot of forward planning and thinking this may be possible, but at least in my experience the vast majority vary the look depending on context. Now you can argue about the benefits of rules that look like

    footer nav ul button and footer nav button versus .footer_sub_button and .footer_main_button. But I think they both have their place.

    Especially because inevitably it seems like someone will want to put their specially designed button here at the end of the list of all the other buttons, or something like that where you do need to target very specifically, and then inheritance can start to screw you over when you need to override a bunch of styles for that one exception instead of just targeting two (or more) different specific classes.

    Still, I like the article and it has a lot of great suggestions.

    • 11

      Heydon Pickering

      August 20, 2013 5:35 am

      Sure! You can approach it however you like, in the end. I’m just sharing a workflow that I use, because it helps me personally to stay on the standards straight-and-narrow.

  5. 15

    In theory I appreciate what Heydon is saying and there are many useful takeaways in here. OOCSS shouldn’t be an excuse to disregard good semantics in your html.

    HOWEVER, in practice… this is exactly how I used to code CSS and it led to all of the problems BEM and OOCSS have identified and tried to solve, i.e. the often counterproductive design of the CSS specificity model, massive (slow) selectors, arbitrary class names, granularity issues, and lack of code reusability. I would have to see how you apply your method to a large project to be convinced of its efficacy.

    Your BEM example is also not quite fair (and while you could do BEM that way, it is not usually necessary to add classes to every element unless you have a very complex block you’re working with). The premise behind BEM is thinking about your design in terms of groups of elements (blocks) that are always found together and ONLY using descendent selectors within these elements so as to avoid selector conflicts and specificity issues. In practice, this actually frees you up from using loads of classes where they’re not necessary.

    What I did take away from this article is how many attributes I was unaware or only vaguely aware of, and how (like Jens Grochtdreis pointed out above) these can be used to enhance my BEM selectors and simplify html markup. In a complex visual design, classes are still absolutely necessary, but may only need to be applied in many cases on the block parent element.

    • 16

      Heydon Pickering

      August 20, 2013 8:05 am

      Sure, that sounds good.

      Just wondering, though…

      If I’m permitted to use descendant selectors within individual modules, I’m wondering why BEM’s example has the classes on each <li> within the <ul>?

      • 17

        The reasons for having a class on each li element:

        1. You are going to have child li elements within those li elements that you don’t want to inherit the parent li’s styles. Using “menu > li” instead of “menu li” will usually take care of this without having to use the extra classes, however.

        2. You are very concerned about selector performance. Using a class directly means that the browser doesn’t have to search all li elements and then narrow down to those with a parent .menu class. Or at least that’s what I’ve been told.

        If I need to use a class within a block, I will prefix it with the block name (i.e. .menu-first) and select it with just the class (no decendant), since this gives me a new namespace to work with and makes it easy to keep all my block definitions together, but if a class isn’t necessary within a block and isn’t going to cause a lot of issues down the road, I won’t use it. “.menu > li” is perfectly acceptable and usually preferable. Once your selectors start getting too deep you’re going to start fighting with specificity, though.

        I really wish specificity had been handled some other way in CSS. Things could have been much different.

  6. 18

    Yes, I did appreciate the irony of the bookmarklet triggering the pink warning.

    I am also trying to decide if I’m happy or sad that Comic Sans does not actually appear on Ubuntu!

    That aside, very enjoyable article, and I think I like the idea of seeing if I can’t do _something_ to add that kind of test into the build process, to remind myself of what Not To Do.

    • 19

      Heydon Pickering

      August 20, 2013 3:50 am

      Winner! 10 points to you :-)

      Perhaps I should have abstracted the “add to bookmarks” function and used a button / .AddFavourite() function combination or similar (

      You know, if I was going to do it properly…

      • 20

        The one thing I am curious about is how this affects performance? Have you done any tests on it? (I know that the CSS linter frowns on ‘selectors that look like regex’: )

        • 21

          Marian Vasile

          August 21, 2013 9:27 am

          Regarding performance of CSS for complex selectors: my approach is to adapt my CSS performance to the dynamic design of the page; the browser can do pretty well with very complex CSS if your page is rendered once. However, if you have animations that reflow the DOM elements, the browser will recalculate some or all CSS. Even so, the most problematic is not the regex search of the DOM (unless you have tens of thousands of tags), but the transparencies, transitions, etc. Not all browsers use the GPU effectively for CSS rendering.

          One other situation you have to test is browser window resize. I’ve seen some pretty heavy CSSed pages (regex and all) that cause no problems at all when resizing my window, and I’ve seen some simpler CSS but with lots of transparency, animations, reflowing rules etc, which made the resizing feel like extreme stuttering.

          • 22

            Heydon Pickering

            August 21, 2013 11:02 am

            A good point. The complexity of rendering via whatever selector is a much bigger performance question than the selector used to invoke that rendering.

  7. 23

    Henrik Kjelsberg

    August 20, 2013 3:38 am

    You’ve pointed out some obvious issues with OOCSS. OOCSS will also become less important as web-components emerge; but what you’ve detailed here, I believe is future-proof. Well done!

  8. 24

    Heydon, do I understand this correctly, you’re saying…

    Do not use additional selectors if styling can be done by:

    – using the correct tag
    – the correct attributes/values

    So (for example) instead of using div.address you’d always go for the address-tag?

    • 25

      Heydon Pickering

      August 20, 2013 4:52 am

      Certainly. By using a class as the styling hook you are not addressing the true nature of the element. Instead you are just addressing what the author (perhaps oneself) has decided that element is.

      This can lead to drifting away from proper standards.

      • 26


        • 27

          I second this… How?

          • 28

            Heydon Pickering

            August 21, 2013 10:58 am

            I’m tempted to say “just read the article again”. Alas, I don’t think you’ll be satisfied with that.

            Instead, lets break it down:

            1. The .button class selector can be used to style anything as a “button”
            2. The button element selector can only be used to style a true, accessible, interoperable, standardised <button> element as a “button”

            Do you see the advantages of (2) over (1)?

      • 29

        This is nothing to do with standards. There’s nothing in standards about how you choose to target an element for styling.

      • 30

        So it’s an advantage that you can only style a button to look like a button. What do you do when you need to style a link like a button?

  9. 31

    Obviously a “button” must have hurt you in the past and I hope you find some comfort in the positive responses your article has had.

    Lots to think about and will help keep the importance of semantic markup at the forefront.

  10. 33

    This is a ridiculous example:

    <button class="button">This is a button</button>

    Classes are meant to separated into theme and layout styles.

    If you were using OCSS properly it would look something more like this:

    <button class="theme-name w1of3">This is a button</button>

    Secondly, the css you’re writing goes against best practices from Mozilla and Google:
    1) Attribute selectors are less efficient
    2) Universal rules are less efficient
    3) Chained selectors are less efficient

    and you’re using all three of them!

    • 34

      Heydon Pickering

      August 20, 2013 5:54 am

      CSS selctor performance hardly matters in most cases; not compared to image weight or javascript performance by a long shot. In addition, it is actually improving for the complex selectors you have listed. The following post addresses these improvements and was written by the inventor of OOCSS, Nicole Sullivan:

      If you were using OCSS properly it would look something more like this:
      <button class=”theme-name w1of3″>This is a button</button>

      You can do that if you like, but it scares the heck out of me :-O

      • 35

        I agree with Heydon. OOCSS becomes far too weighty, far too verbose, and far too difficult to code (you have to remember all the classes, sub-classes, sub-sub-classes, etc. that you invented). If you aim to instead use more element/attribute combinators, you can still use themes with ease by merely relying upon the cascade to *add* theme styles to the existing semantic rules, as it were. If that makes sense.

        However, I do wonder about grids, at least until we actually get an official CSS spec for how to do them without classes. Thoughts?

        • 36

          Heydon Pickering

          August 22, 2013 7:30 am

          you have to remember all the classes, sub-classes, sub-sub-classes, etc. that you invented

          Absolutely. And the key word here is “invented”.

          Thanks for reading, Chris!

        • 37

          As for grids, you have many ways to not have to use classes (or very sparingly) via using a preprocessor such as Sass, Grid systems powered by Sass such as singularitygs, Suzy, and Foundation; and semantic grid systems.

          • 38

            Heydon Pickering

            August 22, 2013 12:43 pm

            You raise a good point and I’m not strongly opposed to grids being powered by classes, but I’m not sure what you mean by “semantic grid system”, Kevin? Do you have an example?

            Surely grids should be powered using <div>s, because they’re just unsemantic scaffolding.

          • 39

            I believe that when Kevin means when he says ‘semantic’ is ‘semantic-to-the-developer’, not ‘semantic-to-the-document-parser’. A few people have written on different levels of semantics: the difference between semantic markup and classnames that mean something to someone who’s reading the source code (e.g., a class like ‘call-to-action’ is better than something like ‘big-and-red’). Think of it as ‘semantic lite’.

            (Unfortunately I can’t reference any of the articles I’ve read recently, because I don’t know where I found them.)

            Semantic grids pretty much require a CSS preprocessor. What you do is give your gridded element a meaningful name: let’s say ‘.categories’ rather than ‘.grid-1-span-3’. Then you use your CSS preprocessor to give .categories the grid styling.

            .categories {
            @media (min-width: 48em) {
            @include grid($start: 1, $span: 3);

            Something like that. The nice thing about this is, because the classnames are decoupled from presentation entirely (all the HTML knows is that it has a class of ‘categories’) you can make it behave differently at different breakpoints (you can see above that my .categories element will only be part of a grid when the viewport is 48em or larger). Try to do that with a plain-CSS grid framework!

            Anyhow, I think this fits in nicely with Heydon’s recommendations; you’d use these classes for when styling based on document semantics just doesn’t cut it.

  11. 40

    Thank you! Great article. I’ve been able to use class-less CSS with at most two-level selectors (e.g., “footer p”) in all my websites. Jeff Starr’s H5 template for WordPress provides an inspiring example, too. It’s actually not that hard, and has surely made for a lot less work. As you say, “Life is too short,” and I’m a lazy cuss.

  12. 41

    Jordan Egstad

    August 20, 2013 5:40 am

    Thank you for the post here, Heydon. I thought the overall message was quite helpful to both those who are learning CSS and have used it on an Intermediate, and possibly even expert, level.

    One of my concerns with this method is scalability. I think a lot can be said about performance here – though from my experience, browsers have less and less trouble with style hooks with practically each update.

    Another angle which should be considered is readability. One of the benefits with SMACCS, BEM, or OOCSS in general, is that developer(s) can quickly read and understand the codebase architecture, which is incredibly valuable– especially when it’s a large scale project.

    All of this to say, it depends on the project. This is certainly a great solution, but not an absolute one. I think a more well-rounded approach would be to use a variety of CSS selectors, they are all there for a reason, and serve a useful purpose(s). As with anything, we as developers must focus on using them wisely.

    Thanks for sharing, man! Really appreciate you sharing your perspective here.

  13. 42

    First, a minor correction for what I hope was a typo:

    Use a button element with type=”disabled”.

    I assume you meant to write:

    use a button element with disabled=”disabled”

    So with that out of the way, I would remind you that anchors are perfectly valid without [href] attributes. Particularly because they were designed to not only be links to other pages, but anchors to content within the page. Be sure to verify that an anchor that does not have an [href] attribute at least has an [id] or [name] attribute because then it would be a named anchor used for navigation within the page. Additionally, it could simply be a placeholder for where a link could be.

    Additionally, the link role is an extension of the button role. All links are buttons, not all buttons are links.

    • 43

      Heydon Pickering

      August 20, 2013 7:55 am

      Actually, the name attribute is obsolete ( and any hyperlink that does not include an href is now considered a placeholder link, not an anchor. Any ID can be used for in-page navigation so there’s no need to produce spurious (placeholder) hyperlinks for the task.

      RE “type=disbaled”: Not so much a typo as me getting in a muddle :-) I saw the error and corrected straight away.

  14. 44

    I really love this article. OOCSS has never felt quite right to me. It’s always seemed overbearing and too difficult to properly implement in the majority of my projects, but I’ve never been presented with an alternative that seemed any better.

    That said, I’m not sure how this method would function in a large project. How do you style modules and wrappers and elements like divs, sections, and asides? Do you continue to rely on various role types?

    • 45

      Heydon Pickering

      August 20, 2013 12:48 pm

      One option is to use RDFa. You can use linked data attributes to semantically define and therefore style all sorts of things; articles, products, people, recipes etc etc. Could each one of these items be considered a “module”, I wonder?

  15. 46

    Thank you for bringing attribute selectors back to the conversation. OOCSS has its benefits, but we’ve got to remember the foundation of semantic markup. I also appreciate your attention to accessibility. My testing shows mixed support for the generated content. Static strings tend to be announced by screen readers, but auto-generating content, such as counts, may not be annnounced.

    I wrote a similar article in 2006 to address the lang and hreflang attributes. I still use the CSS whenever building an international web site.

  16. 47

    Mustafa Kurtuldu

    August 20, 2013 8:30 am

    In using these type of selectors, do they cause any slow down with CSS rendering? Was looking for bench marks online but there doesnt seem to be an official “use x and everything will grind down”. The reason i ask is that i remember a dev telling me a while back that targeting tags slowed web pages down alot.

    Great post by the way.

  17. 50

    I love the entire concept of this article – it really goes with the way I’ve been trying to work for years now.

    Having said that, it entirely depends exactly how complex the design is!

    Lets take the buttons as an example.
    In a design, I have a red button, a green button and a blue button. Without classes, how could I add these different button colors?
    I’m guessing by using role?
    roll=”cancel” or roll=”submit” ?

    Great, but hold on, the ‘submit’ button in the design is larger than the ‘cancel’ button for some layouts, but not for others. So, do we use role on the parent container?

    Ok, that’s do-able, but what about grids?

    • 51

      Tyler Shuster

      August 20, 2013 9:00 am

      If you’re putting something in a strict grid, the semantic solution is really to use a table, though they went through a pretty dark period.

  18. 52

    Tyler Shuster

    August 20, 2013 8:58 am

    Great article! I’m working on a framework which allows users to write 99% classless, 100% semantic HTML. Seeing the sea of frameworks which use things like , makes me cringe, so it’s good to see others are working towards a web that organizes “thingnesses” better. I trust you don’t mind me using your Auticon idea on a larger scale!

    • 53

      Heydon Pickering

      August 20, 2013 12:36 pm

      Not at all. I steal most of my ideas from @w3c’s HTML specification anyway ;-)

  19. 54

    you should really make the font size in the comments !important so people can’t do this

  20. 55

    You’ve hit on something interesting, but missed a powerful extension of this: Using ARIA states such as aria-invalid to style feedback or output elements. This is something my team is currently working on integrating, and it’s made both our HTML and our CSS much clearer to new readers.

    • 56

      Heydon Pickering

      August 20, 2013 12:32 pm

      Spot on, Ted! I couldn’t agree more!

      Actually, I wanted to do a section dedicated to using ARIA state-related attributes as styling hooks but, alas, I got carried away with the other stuff.

      A basic example would be

      [aria-invalid="true"] {
      border: 2px solid red;

      Another “state” example that springs to mind:

      [aria-expanded="false"] {
      height: 0;

      [aria-expanded="true"] {
      height: auto;

      Sounds like what you and the team are doing is pretty great!

      • 57

        Frederik Krautwald

        September 9, 2013 6:01 pm

        I would have loved if attribute key-values were reversed. E.g., instead of aria-invalid=”true”, we could have aria-state=”invalid”; and instead of aria-expanded=”true”, we could have aria-state=”expanded”. These could even be combined, like, aria-state=”invalid expanded”.

        This approach makes more sense from a development point-of-view. At least this approach was taken with the type attribute for input elements.


↑ Back to top