Challenging CSS Best Practices

Advertisement

Editor’s Note: This article features techniques that are used in practice by Yahoo! and question coding techniques that we are used to today. You might be interested in reading Decoupling HTML From CSS1 by Jonathan Snook, On HTML Elements Identifiers2 by Tim Huegdon and Atomic Design With Sass3 by Robin Rendle as well. Please keep in mind: some of the mentioned techniques are not considered to be best practices.

When it comes to CSS, I believe that the sacred principle of “separation of concerns4” (SoC) has lead us to accept bloat, obsolescence, redundancy, poor caching and more. Now, I’m convinced that the only way to improve how we author style sheets is by moving away from this principle.

For those of you who have never heard of the SoC principle in the context of Web design, it relates to something commonly known as the “separation of the three layers”:

  • structure,
  • presentation,
  • behavior.

It is about dividing these concerns into separate resources: an HTML document, one or more cascading style sheets and one or more JavaScript files.

But when it comes to the presentational layer, “best practice” goes way beyond the separation of resources. CSS authors thrive on styling documents entirely through style sheets, an approach that has been sanctified by Dave Shea5’s excellent project CSS Zen Garden6. CSS Zen Garden is what most — if not all — developers consider to be the standard for how to author style sheets.

The Standard

To help me illustrate issues related to today’s best practices, I’ll use a very common pattern: the media object7. Its combination of markup and CSS will be our starting point.

Markup

In our markup, a wrapper (div.media) contains an image wrapped in a link (a.img), followed by a div (div.bd):

<div class="media">
  <a href="http://twitter.com/thierrykoblentz" class="img">
        <img src="thierry.jpg" alt="me" width="40" />
  </a>
  <div class="bd">
    @thierrykoblentz 14 minutes ago
  </div>
</div>

CSS

Let’s give a 10-pixel margin to the wrapper and style both the wrapper and div.bd as block-formatting contexts8 (BFC). In other words, the wrapper will contain the floated link, and the content of div.bd will not wrap around said link. A gutter between the image and text is created with a 10-pixel margin (on the float):

.media {
    margin: 10px;
}
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}

Result

Here is the presentation of the wrapper, with the image in the link and the blob of text:


me
9

@thierrykoblentz 14 minutes ago

A New Requirement Comes In

Suppose we now need to be able to display the image on the other side of the text as well.

Markup

Thanks to the magic of BFC, all we need to do is change the styles of the link. For this, we use a new class, imgExt.

<div class="media">
    <a href="http://twitter.com/thierrykoblentz" class="imgExt">
        <img src="thierry.jpg" alt="me" width="40" />
  </a>
  <div class="bd">
    @thierrykoblentz 14 minutes ago
  </div>
</div>

CSS

We’ll add an extra rule to float the link to the right and change its margin:

.media {
    margin: 10px;
}
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}
.media .imgExt {
    float: right;
    margin-left: 10px;
}

Result

The image is now displayed on the opposite side:


me
10

@thierrykoblentz 14 minutes ago

One More Requirement Comes In

Suppose we now need to make the text smaller when this module is inside the right rail of the page. To do that, we create a new rule, using #rightRail as a contextual selector:

Markup

Our module is now inside a div#rightRail container:

<div id="rightRail">
    <div class="media">
        <a href="http://twitter.com/thierrykoblentz" class="img">
            <img src="thierry.jpg" alt="me" width="40" />
        </a>
        <div class="bd">
            @thierrykoblentz 14 minutes ago
        </div>
    </div>
</div>

CSS

Again, we create an extra rule, this time using a descendant selector, #rightRail .bd.

.media {
    margin: 10px;
}
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}
.media .imgExt {
    float: right;
    margin-left: 10px;
}
#rightRail .bd {
    font-size: smaller;
}

Result

Here is our original module, showing inside div#rightRail:


me
11

@thierrykoblentz 14 minutes ago

What’s Wrong With This Model?

  • Simple changes to the style of our module have resulted in new rules in the style sheet.
    There must be a way to style things without always having to write more CSS rules.
  • We are grouping selectors for common styles (.media,.bd {}).
    Grouping selectors, rather than using a class associated with these styles, will lead to more CSS.
  • Of our six rules, four are context-based.
    Rules that are context-specific are hard to maintain. Styles related to such rules are not very reusable.
  • RTL and LTR interfaces become complicated.
    To change direction, we’d need to overwrite some of our styles (i.e. write more rules). For example:
.rtl .media .img {
    margin-right: auto; /* reset */
    float: right;
    margin-left: 10px;
}
.rtl .media .imgExt {
    margin-left: auto; /* reset */
    float: left;
    margin-right: 10px;
}

Meet Atomic Cascading Style Sheet

a·tom·ic12
/ə’tämik/
of or forming a single irreducible unit or component in a larger system.

As we all know, the smaller the unit, the more reusable it is.

To break down styles into irreducible units, we can map classes to a single style, rather than many. This will result in a more granular palette of rules, which in turn improves reusability.

Let’s revisit the media object using this new approach.

Markup

We are using five classes, none of which are related to content:

<div class="Bfc M-10">
    <a href="http://twitter.com/thierrykoblentz" class="Fl-start Mend-10">
        <img src="thierry.jpg" alt="me" width="40" />
    </a>
    <div class="Bfc Fz-s">
        @thierrykoblentz 14 minutes ago
    </div>
</div>

CSS

Each class is associated with one particular style. For the most part, this means we have one declaration per rule.

.Bfc {
    overflow: hidden;
    zoom: 1;
}
.M-10 {
    margin: 10px;
}
.Fl-start {
    float: left;
}
.Mend-10 {
    margin-right: 10px;
}
.Fz-s {
    font-size: smaller;
}

Result


me
17

@thierrykoblentz 14 minutes ago

What Is This about?

Let’s ignore the class names for now and focus on what this does (or does not):

  • No contextual styling
    We do not use contextual or descendant selectors, which means that our style sheet has no dead weight.
  • Directions (left and right) are “abstracted.”
    Rather than overwriting styles, we serve a RTL style sheet that contains rules such as these:
.Fl-start {
    float: right;
}
.Mend-10 {
    margin-left: 10px;
}

Same classes, same properties, different values.

But the most important thing to notice here is that we are styling via markup. We have changed the context in which we style our modules. We are now editing HTML templates instead of style sheets.

I believe that this approach is a game-changer because it narrows the scope dramatically. We are styling not in the global scope (the style sheet), but at the module and block level. We can change the style of a module without worrying about breaking something else on the page. And we can do this without adding any rule to the style sheet, let alone creating a new class and rule:

.someBasicStyleForThisElementHere {...}

We get no redundancy. Selectors are not duplicated, and styles belong to a single rule instead of being part of many. For example, the style sheets that this page links to contain 72 float declarations.

Also, abandoning a style — for example, deciding to always keep the image on the left side of the module — does not make any of our rules obsolete.

Sound Good?

Not sold yet? I hear you saying, “This goes against every single rule in the book. This is no better than inline styling. And your class names are not only cryptic, but unsemantic, too!”

Fair enough. Let’s address these concerns.

Regarding Unsemantic Class Names

If you check the W3C’s “Tips for Webmasters18,” where it says “Good names don’t change,” you’ll see that the argument is about maintenance, not semantics per se. All it says is that changing styles is easier in a CSS file than in multiple HTML files. .border4px would be a bad name only if changing the style of an element required us to change the declaration that that class name is associated with. In other words:

.border4px {border-width:2px;}

Regarding Cryptic Class Names

For the most part, these class names follow the syntax of Zen Coding — see the “Zen Coding Cheat Sheet19” (PDF) — now renamed Emmet20. In other words, they are simple abbreviations.

There are exceptions for styles associated with direction (left and right) and styles that involve a combination of declarations. For example, Bfc stands for “block-formatting context.”

Regarding Mimicking Inline Styles

Hopefully, the diagram below clears things up:

Venn diagram that shows all possible logical relations between inline styles and styling via classes and markup.21
Inline styles versus Atomic CSS.

  • Specificity
    The technique is not as specific as @style. It lowers style weight because rules rely on a single class, as opposed to rules like .parent .bd {}, which clocks in at 0.0.2.0 (see “CSS Specificity: Things You Should Know22”).
  • Verbosity
    Most classes are abbreviations of declarations (for example, M-10 versus margin: 10px). Some classes, such as Bfc, refer to more than one style (see “Mapping” in the diagram above). Other classes use “start” and “end” keywords, rather than left and right values (see “Abstraction” in the diagram above).

Here are the advantages of @style:

  • Scope
    Styles are “sandboxed” to the nodes they are attached to.
  • Portability
    Because the styles are “encapsulated,” you can move modules around without losing their styles. Of course, we still need the style sheet; however, because we are making context irrelevant, modules can live anywhere on a page, website or even network.

The Path To Bloat

Because the styles of our module are tied only to presentational class names, they can be anything we want them to be. For example, if we need to create a simple two-column layout, all we need to do is replace the link with a div in our template. That would look like this:

<div class="Bfc M-10">
    <div class="Fl-start Mend-10 W-25">
        column 1
    </div>
    <div class="Bfc">
        column 2
    </div>
</div>

And we would need only one extra rule in the style sheet:

.Bfc {
    overflow: hidden;
    zoom: 1;
}
.M-10 {
    margin: 10px;
}
.Fl-start {
    float: left;
}
.Mend-10 {
    margin-right: 10px;
}
.Fz-s {
    font-size: smaller;
}
.W-50 {
    width: 50%;
}

Compare this to the traditional way:

<div class="wrapper">
    <div class="sidebar">
        column 1
    </div>
    <div class="content">
        sidebar
    </div>
</div>

This would require us to create three new classes, to add an extra rule and to group selectors.

.wrapper,
.content,
.media,
.bd {
    overflow: hidden;
    _overflow: visible;
    zoom: 1;
}
.sidebar {
    width: 50%;
}
.sidebar,
.media .img {
    float: left;
    margin-right: 10px;
}
.media .img img {
    display: block;
}

I think the code above pretty well demonstrates the price we pay for following the SoC principle. In my experience, all it does is grow style sheets.

Moreover, the larger the files, the more complex the rules and selectors become. And then no one would dare edit the existing rules:

  • We leave alone rules that we suspect to be obsolete for fear of breaking something.
  • We create new rules, rather than modify existing ones, because we are not sure the latter is 100% safe.

In other words, we make things worse because we can get away with bloat.

Nowadays, people are accustomed to very large style sheets, and many authors think they come with the territory. Rather than fighting bloat, they use tools (i.e. preprocessors) to help them deal with it. Chris Eppstein tells us23:

“LinkedIn has over 1,100 Sass files (230k lines of SCSS) and over 90 web developers writing Sass every day.”

CSS Bloat vs. HTML Bloat

Let’s face it: the data has to live somewhere. Consider these two blocks:

<div class="sidebar">
<div class="Fl-start Mend-10 W-25">

In many cases, the “semantic” class name makes up more bytes than the presentational class name (.wrapper versus .Bfc). But I do not think this is a real concern compared to what most apps onboard these days via data- attributes.

This is where gzip24 comes into play, because the high redundancy in class names across a document would achieve better compression. And the same is true of style sheets, in which we have many redundant sequences:

.M-1 {margin: 1px;}
.M-2 {margin: 2px;}
.M-4 {margin: 4px;}
.M-6 {margin: 6px;}
.M-8 {margin: 8px;}
etc.

Caching

Presentational rules do not change. Style sheets made from such rules mature into tool sets in which authors can find everything they need. By their nature, they stop growing and become immutable, and immutable is cache-friendly.

No More .button Class?

The technique I’m discussing here is not about banning “semantic” class names or rules that group many declarations. The idea is to reevaluate the benefits of the common approach, rather than adopting it as the de facto technique for styling Web pages. In other words, we are restricting the “component” approach to the few cases in which it makes the most sense.

For example, you may find the following rules in our style sheets, rules that set styles for which we do not create simple classes or rules that ensure cross-browser support.

.button {
    display: inline-block;
    *display: inline;
    zoom: 1;
    font-size: bold 16px/2em Arial;
    height: 2em;
    box-shadow: inset 1px 1px 2px 0px #fff;
    background: -webkit-gradient(linear, left top, left bottom, color-stop(0.05, #ededed), color-stop(1, #dfdfdf));
    background: linear-gradient(center top, #ededed 5%, #dfdfdf 100%);
    filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ededed', endColorstr='#dfdfdf');
    background-color: #ededed;
    color: #777;
    text-decoration: none;
    text-align: center;
    text-shadow: 1px 1px 2px #ffffff;
    border-radius: 4px;
    border: 2px solid #dcdcdc;
}
.modal {
    position: fixed;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
    *width: 600px;
    *margin-left: -300px;
    *top: 50px;
}
@media \0screen {
    .modal {
        width: 600px;
        margin-left: -300px;
        top: 50px;
    }
}

On the other hand, you would not see rules like the ones below (i.e. styles bound to particular modules), because we prefer to apply these same styles using multiple classes: one for font size, one for color, one for floats, etc.

.news-module {
    font-size: 14px;
    color: #555;
    float: left;
    width: 50%;
    padding: 10px;
    margin-right: 10px;
}
.testimonial {
    font-size: 16px;
    font-style: italic;
    color: #222;
    padding: 10px;
}

Do We Include Every Possible Style In Our Style Sheet?

The idea is to have a pool of rules that authors can choose from to style anything they want. Styles that are common enough across a website would become part of the style sheet. If a style is too specific, then we’d rely on @style (the style attribute). In other words, we’d prefer to pollute the markup rather than the style sheet. The primary goal is to create a sheet made of rules that address various design patterns, from a basic rule that floats an element to “helper” classes.

/**
 * one liner with ellipsis
 * 1. we inherit hyphens:auto from body, which would break "Ell" in table cells
 */
.Ell {
    max-width: 100%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    -webkit-hyphens: none; /* 1 */
    -ms-hyphens: none;
    -o-hyphens: none;
    hyphens: none;
}
/**
 * kinda line-clamp
 * two lines according to default font-size and line-height
 */
.LineClamp {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;
    font-size: 13px;
    line-height: 1.25;
    max-height: 32px;
    _height: 32px;
    overflow: hidden;
}
/**
 * reveals an hidden element on :hover or :focus
 * visibility can be forced by applying the class "RevealNested-on"
 * IE8+
 */
:root .NestedHidden {
    opacity: 0;
}
:root .NestedHidden:focus,
:root .RevealNested:hover .NestedHidden,
:root .RevealNested-on .NestedHidden {
    opacity: 1;
}

How Does This Scale?

We have just released a brand new My Yahoo25, which relies heavily on this technique. This is how it compares to a few other Yahoo products (after gzip’ing):

CSS Assets
answers.yahoo.com 30.1 KB
sports.yahoo.com 67.4 KB
omg.yahoo.com 46.2 KB
yahoo.com 45.9 KB
my.yahoo.com 21.3 KB

Our style sheet weighs 17.9 KB (about 3 KB of which are property-specific), and it is shareable (unlike the style sheets of other properties). The reason for this is that none of the rules it contains relate to content.

Wrapping Up

Because presentational class names have always been deemed “out of bounds,” we — the community — have not really investigated what their use entails. In fact, in the name of best practice, we’ve dismissed every opportunity to explore their potential benefits.

Here at Yahoo, @renatoiwa26, @StevenRCarlson27 and I28 are developing projects with this new CSS architecture29. The code appears to be predictable, reusable, maintainable and scalable. These are the results we’ve experienced so far:

  • Less bloat
    We can build entire modules without adding a single line to the style sheets.
  • Faster development
    Styles are driven by classes that are not related to content, so we can copy and paste existing modules to get started.
  • RTL interface for free
    Using start and end keywords makes a lot of sense. It saves us from having to write extra rules for RTL context.
  • Better caching
    A huge chunk of CSS can be shared across products and properties.
  • Very little maintenance (on the CSS side)
    Only a small set of rules are meant to change over time.
  • Less abstraction
    There is no need to look for rules in a style sheet to figure out the styling of a template. It’s all in the markup.
  • Third-party development
    A third party can hand us a template without having to attach a style sheet (or a style block) to it. No custom rules from third parties means no risk of breakage due to rules that have not been properly namespaced.

(Note that if maintenance is easier on the CSS side than on the HTML side, then the reason is simply that we can cheat on the CSS side by not cleaning up rules. But if we were required to keep things lean and clean, then the pain would be the same.)

Final Note

I was at a meetup30 a couple of weeks ago, where I heard Colt McAnlis say, “Tools, not rules31.” A quick search for this idiom returned this32:

“We all need to be open to new learnings, new approaches, new best practices and we need to be able to share them.”

(al, ea)

Footnotes

  1. 1 http://www.smashingmagazine.com/2012/04/20/decoupling-html-from-css/
  2. 2 http://nefariousdesigns.co.uk/on-html-element-identifiers.html
  3. 3 http://www.smashingmagazine.com/2013/08/02/other-interface-atomic-design-sass/
  4. 4 http://en.wikipedia.org/wiki/Separation_of_concerns
  5. 5 http://www.mezzoblue.com/
  6. 6 http://www.csszengarden.com/
  7. 7 http://www.stubbornella.org/content/2010/06/25/the-media-object-saves-hundreds-of-lines-of-code/
  8. 8 http://www.yuiblog.com/blog/2010/05/19/css-101-block-formatting-contexts/
  9. 9 http://twitter.com/thierrykoblentz
  10. 10 http://twitter.com/thierrykoblentz
  11. 11 http://twitter.com/thierrykoblentz
  12. 12 https://www.google.com/search?q=define%3A+atomic
  13. 13 https://twitter.com/csswizardry
  14. 14 https://twitter.com/stubbornella
  15. 15 https://twitter.com/search?q=%23btconf&src=hash
  16. 16 https://twitter.com/smashingmag/statuses/339024926197559296
  17. 17 http://twitter.com/thierrykoblentz
  18. 18 http://www.w3.org/QA/Tips/goodclassnames
  19. 19 https://zen-coding.googlecode.com/files/ZenCodingCheatSheet.pdf
  20. 20 http://docs.emmet.io/cheat-sheet/
  21. 21 http://www.smashingmagazine.com/wp-content/uploads/2013/10/venn-diagram_mini.png
  22. 22 http://www.smashingmagazine.com/2007/07/27/css-specificity-things-you-should-know/
  23. 23 http://chriseppstein.github.io/blog/2013/04/22/joining-linkedin/
  24. 24 http://www.gzip.org/
  25. 25 http://my.yahoo.com
  26. 26 https://twitter.com/renatoiwa
  27. 27 https://twitter.com/StevenRCarlson
  28. 28 https://twitter.com/thierrykoblentz
  29. 29 http://engineering.appfolio.com/2012/11/16/css-architecture/
  30. 30 http://www.meetup.com/sfhtml5/events/131694202/
  31. 31 https://www.youtube.com/watch?v=OPBvdsFi7Ss&feature=player_detailpage#t=11041
  32. 32 http://notrulestools.com/Main_Page

↑ Back to topShare on Twitter

Thierry is passionate about Web Design and CSS. He loves the challenge of solving problems and dreaming up original ideas that get him out of bed in the morning and keep him working late at night. He is a front-end engineer at Yahoo! and owns TJK Design, css-101.org and ez-css.org. His twitter handle is @thierrykoblentz.

Advertising
  1. 1

    Gunnar Bittersmann

    October 21, 2013 3:29 am

    “To help me illustrate issues related to today’s best practices, I’ll use a very common pattern:” div div div

    C’mon, we can do better than that! figure and figcaption elements exist.

    -4
    • 2

      This is *not* my code. And the reason why I did not use my own code is because I *knew* some people would be more interested in discussing my choice of tags than discussing the topic of the article :)

      0
      • 3

        Gunnar Bittersmann

        October 22, 2013 11:47 pm

        If you use foreign code in your article, it becomes *your* code. You can’t deny your responsibility.

        Like it or not, people will copy and paste sample code without further thinking. So when you give examples, give good ones!

        And BTW, in this case not figcaption would be the appropriate element as I might have suggested, but footer.

        -2
  2. 4

    Used to use this approach with my team for about a year. I will never do such again. You’re forgetting a crucially cost, that of human effort. Now if all your markup is dynamically generated this approach is fine. But consider a situation in which multiples of a single type of object all have a margin right of 10px . The class used for margin right is also used by another object type. For some reason you need to change the margin right on the first but not the second to 15px. If your classes and CSS had been object oriented you could have easily changed the margin for one of the object types and kept the other fine. Instead you need to make a new class and replace all of the existing instances in the html. Further, this can lead to a lot of confusing classes made for little fixes like this. Granted, I come from a client work based background where this proved disastrous when it came to revisions. A in house team, using dynamically generated html5 and classes should have little problem with this approach. For the rest of us, I highly discourage this way of maintaining our styles.

    1
    • 5

      This is exactly what I was going to post. The approach moves way too much work and maintenance into the HTML. Sure, class names have no semantic value, but they do have “human value” – seeing code littered with bfc and m10 is unintuitive for developers.

      Also, this seems like a real headache for actual development. If you are for example trying out several spacing values for something, instead of changing one number in a stylesheet back and forth, you need to change dozens of class names every time.

      1
    • 6

      Marcello Damasceno

      October 21, 2013 9:35 am

      +1. His technique is pretty much html inline styling, and as a responsive web applications designer, it would be nightmare to work with. I’ll stick to my OOCSS, thank you.

      0
      • 7

        +1 (Where’s my god damn vote button, Smashing?)

        This is no longer instantly understandable code. Do you apply that naming convention to your js functions too? Php objects? Variables?

        Way too hard to read.

        0
        • 8

          Here is how I see it:

          If you are experienced with CSS then markup such as this
          <div class="m10 bgWhite"></div>
          is very quick and easy to understand. You don’t even have to go in to your CSS to know that m10 will apply {margin: 10px} and bgWhite {background-color: #fff}.

          On the other hand code like
          <div class="content-container"></div>
          will force you to find the appropriate class selector to know what it does. This in not a big effort if you have good tools, but it adds up.
          Now, if you have very little experience with CSS then I totally agree that it’s easier to understand content-container. It is something that wraps content. But your understanding would still be on another level where it might be easier for you to reuse but not easier to configure.

          0
          • 9

            You’ve heard of Firebug, right?

            1
          • 10


            is very quick and easy to understand. You don’t even have to go in to your CSS to know that m10 will apply {margin: 10px} and bgWhite {background-color: #fff}.

            Well, no, you don’t actually know the CSS will do that. It’s a reasonable expectation, but if you need that item to now have a background of light yellow and a margin of 8px you either live with a mismatch or you alter your markup just because of a visual style change which strikes me as silly.

            Also, you do not know m10 refers to a 10 pixel margin unless you also know that all margins are defined in pixels and not rems, ems, or percentages.

            3
  3. 11

    Isn’t this what Twitter bootstrap does?

    It really depends on the size of the project. For a large project it could be useful but it would be slower for a contractor or new employee to understand the code as they will first need a thorough knowledge of the the CSS units before they start writing any production code.

    3
  4. 12

    Hi Thierry, some of your points make good sense. However, I think you’ve taken the idea of multiple classes to be a bit too granular. I can understand having a few classes that implement regular styles but applying an individual style to an individual class is incorrect in my opinion.

    I would normally have the following: .left (float: left), .right (float: right), .clear (clear: both). Then possibly .no-margin (margin-bottom: 0). Of course, you could add more but I think you are taking things to the extreme.

    2
  5. 13

    I literally almost fell off my chair,… am I missing something? I can think of so many things that can go wrong with this approach on larger projects. First thing that came to mind was what if a change to the design leads to the margin arround the components to be 20 instead of 10 (.m-10) you’ll have to change this in a dozen of components, flows, templates,… or change the .m-10 {margin:10px; } to .m-10{margin:20px;} what is sooo wrong.. :p

    Also if you’re working with a team you’ll need a manual for the class names…

    1
    • 14

      This technique assumes you are willing to ***switch contexts***. You’d be styling by changing classes in a template instead of editing a styles sheet. In other words, one should not try to use this technique unless one is willing to make that switch.

      Regarding class names: as suggested in this article, the names follow Zen coding syntax (mostly simple abbreviations). We have a Sublime plugin to help us remember the very few “complex” ones.

      1
      • 15

        Maintainability-wise it’s crap. The power of CSS lies in it’s ability to swap the file with another to get a wholly different site.

        This “context” ruins that power. Might as well go inline.

        1
        • 16

          “Might as well go inline.”

          This *is* inline styling, though at the same time it’s a slight improvement on it. It simply removes the duplication you’d get with true inline styles (instead of ‘margin:10px’ repeated many times you have ‘M-10′ and a cached stylesheet).

          Though personally I don’t think it’s enough of an improvement.

          0
          • 17

            (instead of ‘margin:10px’ repeated many times you have ‘M-10′ and a cached stylesheet).

            Doesn’t really matter. When you gzip, both get compressed away to the same filesize.

            1
  6. 18

    Nice article, but the used class names are semantic, too! There is – in my eyes – no difference between naming a class “border4px” or “M-1″ because both names describe the properties and are NOT abstract names.

    0
    • 19

      I agree, I say in the article that “border4px” would be wrong only if it was mapped to a style other than a 4px border…

      0
      • 20

        In this example, if the scope changed and the border should now be 2px, is your solution to make a new CSS class named border2px, then find every occurrence of the class in the html and change it? Your markup and CSS wouldn’t be bloated but that seems impractical.

        0
        • 21

          Yes, we’d be styling via markup – which is not a problem as long as your workflow is setup for this.

          1
          • 22

            which defeats the whole purpose of a “style sheet”

            0
          • 23

            I just have a brief look and i’ve used this method 2 years ago and this method produces weaknesses with RWD if you’re not careful enough.
            For eg: The margin is changed when it’s on mobile version. With something like M-8. You’ll have to change the class name.
            Sometimes it even causes some dead dirty HTML code, I’ve experienced it when i worked for outsourcing company.

            1
          • 24

            No, it is not ok to be defining style in your markup. You can have your cake and eat it too by defining abstract classes. Not M-10 but something like “Vert-Gutter”.

            Maybe you young’ns don’t remember, but this is how us old guys have been doing CSS since it started existing.

            2
      • 25

        I think that the article creates a very good discussion, however I find that I disagree with naming a class “border4px” as it’s very inflexible. If the designer or the client were to ask for 8px’s of padding, you now need to change both the style and the markup.

        I think there are use cases out there for this naming scheme, but I wouldn’t make it a common practice to name things based on their “physical” properties (color, alignment, etc.).

        0
        • 26

          I think you’d just add a new class with 8px, no need to change the current class. Then add the new class in the html tag. It wouldn’t be too redundant to create a new class for every different border-width, because generally you’ll only have a few in your theme. Like b8px, b4px, and b1px, instead of making like 10 of them when you only use 3 widths. It fixes the problem the author mentioned that you’re afraid to edit existing styles out of fear of breaking something. While you do have to create a new style, it at least is a simple one that can be reused.

          0
        • 27

          Also there’s a pretty good chance that you won’t be changing _every_ border to 8px, some modules might need to stay at 4px.

          0
  7. 28

    Imho, a point and some experience :

    => use display: table and display: table-cell :)

    => in my job, I’m also using a personal micro-framework with presentational classes, it allows to limit the growth of the CSS (it works very well with preprocessors and SMACSS approach, with @extend, which allows you to rebuild modules very easily if needed).

    etc.

    As far as I can see, I’ve used extensively these techniques on a website (http://www.pnlcoach.com/ , not to name it), and the result is here : a first load at less than 150 kb, and a very fast render.

    Of course, every technique has its limits. :)

    0
    • 29

      I agree with you. It’s a shame that display: table and display:table-cell get absolutely no love. Everyone is trying to push flex boxes, which aren’t going to be usable for 2-3 years still. The benefit of table/table-cell lies in both it’s backwards compatibility with IE8 and it’s usefulness when designing for responsive. It’s so useful.

      0
  8. 30

    I don’t agree with that way of coding. It’s only about creating classes for single CSS properties. It doesn’t make any sense.
    The only good point might be the caching and ease of using it in other products. But it’s still like writing an inline code.
    IMO, it’s better to keep context in the CSS code, because then you know what’s going on in the specified place.
    It’s better to create some general CSS classes and then extend them in specific context.

    0
    • 31

      Agreed. The whole point of CSS is to remove style definitions from the HTML. Some of these examples are a little too close to inline styling for my taste. Not to mention the terrible class names like .Bfc, which are clearly just that short to try and reduce the added HTML weight.

      0
    • 32

      I totally agree. Seriously, whats the advantage of a class named .m10 over inline-styles?? This is just nonsense, at least not very well thought out. Worse yet, while I know what margin: 10px means I would have to look up if .m10 means margin: 10px or margin: 10em or something else.

      0
    • 33

      “…But it’s still like writing an inline code.”

      “IMO, it’s better to keep context in the CSS code, because then you know what’s going on in the specified place.”

      Agree 100%, that is the point of all coding languages (even html5 and css). They are LANGUAGES, which means semantics and readability hold a high level of importance. That’s why we use section, article, aside, p etc… instead of div everywhere (even though we could make the div work like all above mentioned elements). It adds context that is more readable. Also context is especially important for media queries.

      I also think that conventional css abstraction makes the work of a back end developer rendering html conditionally and looping through mark-up using server-side code, a lot easier.

      Not that I’m totally against the idea. But this is more like css class helpers (for example tbs .pull-left to float an element left) – still it’s a lot like (may be too much like) inline-styling.

      So I don’t see the advantages of this style outweighing it’s disadvantages.

      And Let me add this also: I think that a problem can arise using this style of coding when using jquery addClass method. If I wanted to change the margin, padding & other properties using jquery addClass method.


      $("element").addClass("m-1 p-20");

      This might give me problems depending on the order in which the styles cascade. In other words, if the element already has the class .m-10, (which would be after m-1), adding the class m-1 wouldn’t give the expected result. We’d have to:


      $("element").removeClass("m-10").addClass("m-1 p-20");

      0
      • 34

        I absolutely agree. This approach stops being useful when you have more than one page your styles apply to. If that’s the case, you NEED your classes to be contextual. Otherwise you’re gonna be changing classes on every single page to get one common element right. Sure, with dynamic sites that’s less of a problem, but I can’t see any benefit from doing this.
        To avoid redundance and increase readability, I recommend using SCSS and its variable, extend and mixin features. Then combine that with good semantic namegiving and you’ve got a great, comfortable tool. The few kilobytes more the final css- file will have are well worth it and in my opinion can be ignored. Use gzip on the file and I don’t think there’s anyone out there who’ll have a problem with the page’s speed.

        0
  9. 35

    Hi Thierry,

    I’ve used this technique before with some success. Most difficult part was getting people to ‘buy in’ as you can imagine. I had exactly the response from devs that would expect, e.g. “this is just the same as styling inline”.

    However, with your implementation of this approach I’m curious. When your elements change significantly across viewports (e.g. from a display: block; to become a display: inline; as an example) how do you handle the switch? Do you swap out classes with JS or do you write a particular class to handle it. In this example ‘vps’ would be for ‘viewport specific’:

    .vps-bl {
       /* mobile styles */
    }
    
    @media only screen and (min-width: 18.75em) {
        .vps-bl {
            /* next viewport styles */
        }
    }
    

    Just curious whether you have found either approach preferable?

    0
    • 36

      This is all I could think of reading this: how does it work when mobile optimising? The advantage of more element specific CSS (ie. div id="calendar"… is that if needs be the element can be stripped of all it’s styling bringing it back to pure HTML, which can then be styled entirely differently for a smaller device.

      To clarify, I’m not thinking of things like colours and fonts, but an item that was previously floated and used margins for finer positioning could be completely changed to use absolute or relative positioning.

      Based on your examples and my understanding (I fully accept I might not be understating the full potential yet) this seems ‘impossible’. Without removing and adding classes with JS, you couldn’t simply transform the .M-10 class because one element no longer needs it, you would need to change the class used in the HTML.

      Interested to know if you thought/solved this problem. I notice the MyYahoo site doesn’t change much in the way of mobile device, just the column widths change slightly.

      0
    • 37

      Now, that’s a very good question!

      0
    • 38

      Hi Ben,

      Great question.
      First of all, as the article suggests it is all about context. If you go Adaptive and send different markup to different devices then it’s not much of an issue because that’s where the style lives, in the HTML.
      To address the Responsive approach, we rely on a script that works more or less as a media query but at the element level rather than the viewport.
      We have some logic in a “responsive-grid” styles sheet that allows us to reflow boxes according to arbitrary breakpoints (chosen via the value of a data- attribute). For example (pseudo-code):

      <div>
          <div class='Grid-U-1-3 Bp-1-1'>Box 1</div>
          <div class='Grid-U-1-3 Bp-1-2'>Box 2</div>
          <div class='Grid-U-1-3 Bp-1-2'>Box 3</div>
      </div>
      

      Before the breakpoint is reached, the above shows 3 columns, after what it will display 1 row on top of 2 columns.

      .Grid-U-1-3 stands for one third. It is overwritten by .Bp-1-1 which says make it full row, followed by .Bp-1-2 for 2 equal columns (50/50). The prefix “Bp” stands for “breakpoint”. In the style sheet, you’d find something like this:

      .Grid-U-1-3 {width:33.33%;}
      ...
      .BreakPoint .Bp-1-1 {width:100%;}
      .BreakPoint .Bp-1-2 {width:50%;}

      The cascade does the work for us, overwriting the initial width.

      As a side note, we are also discussing using different classes on the same template/markup, but addressing different devices. At build time, the template would be parsed and only the relevant classes would be written for each context (device). That way we do not deal with duplicating templates in case we serve more or less the same module in which only the classes would be different.

      0
      • 39

        Hi Thierry,

        Thanks for the info. Very interesting as it sounds like we have both independently come to the same technical solution to the issue. Our solution was to read out the metrics of the viewport on the outset (and then on specific events) and store a code in the wrapping elements data- attribute; kind of like a primitive polyfilled ‘Element Query’.

        We’ve actually stepped back from this atomic approach a little in recent months. Purely on the grounds of code readability. It was, at times, becoming impossible others to infer meaning from our HTML. The maintainability and compactness of our CSS was greatly increased but the efficacy of our code for others diminished somewhat. My favoured approach at present is utility classes (e.g. `w15`, `hfull`) to do specific ‘grunt’ tasks such as width/positioning alongside more meaningful classes such as `.main-header-drop` that do heavier lifting specific to the element.

        I’ll be keen to know in 6 months to a year whether you are still using it in the same manner. I suppose much of it will depend on the amount of ‘buy-in’ you get from related teams?

        0
        • 40

          Been using a very similar approach for about 3 years now, doing pure mobile, static and responsive layouts. It holds :)

          During the year there has been a lot of adjustments but the underlying “atomic” philosophy has remained unchanged. The CSS now gets broken down in to three parts to work well with state (media-queries, .active classes, disabled attributes and such) changes.

          Globals:
          Resets default styling for elements. I.e sets default styling for tags, body, div, a, span, p, input tags etc. Never use descendants. Never use !important.

          Framework: (ex. .mt10 {margin-top: 10px})
          Used for referencing specific css properties. Never use descendants. Never use !important. Never use ids. Always use classes.

          Modules:
          Used for classes with multiple functionalities, descendants and/or state dependecies. Never use !important. Never use ids. Prefer class selectors but use attribute selectors when appropriate.

          0
      • 41

        What exactly do you mean by the following statement,

        “we rely on a script that works more or less as a media query but at the element level rather than the viewport.”

        And is this where the .BreakPoint class is added to the dom?

        0
  10. 42

    Are classes more preferred over ids?

    0
    • 43

      I think classes are essential here, the whole point of this technique is to reuse the same classes over and over on the page. You can’t use the same ID twice on a page, so you couldn’t reuse any of the rules. It would defeat the whole point.

      http://css-tricks.com/a-line-in-the-sand/ along with many other articles have argued for a while, that IDs should never be used for styling.

      0
    • 44

      This approach would be impossible with ids since an id only exists once per page.

      0
  11. 45

    Giving short class name is always preferred. But if there are more number of classes which declare only single property, then they will consume more bytes. They become reusable on the other end, but then an element would end up with multiple classes in most cases.

    0
    • 46

      Actually, I believe if you were comparing to examples from the real world, you’d see that it’s not that simple.
      We did an internal check against a few pages at Yahoo and we found out that using ACSS was actually making the HTML smaller. Which makes sense if you look at the average length of class names out there.

      0
      • 47

        I see how ACSS can benefit large networks, even if I see also where it may fall short. You end up having large libraries of instructions that have to match the mark up. In short, you double up the maintenance workload.

        Unfortunately it does not work in my case and I suppose for a large portion of websites, which are much smaller than the whole Yahoo network, and mainly made up with templates which have to share the same markup and being styled differently via their own stylesheet. Sometimes a frontend designer doesn’t even have control on the markup at all and have to learn how to handle stuffs purely via CSS.

        Thanks for sharing, it’s always good to be inspired and challenged in one’s own habits and daily routines. Good food for brain.

        0
  12. 48

    great way to make simple things complicated.

    0
  13. 49

    This is realy useful, as im right now developing a web backend to a big app system, and its being build in modules, and should be scaleable in the form of adding more modules! so this comes at the right time for me! thanks!

    0
  14. 50

    In many ways your ideas sound good. By adding M-10 to something I know that I am adding 10px margin. Great.

    But let’s use your testimonial example. As a server side developer I would prefer to not to have to “know” where my elements are. I want to send my client side code this:

    [bunch of html]

    and then let the designer know there is a class called testimonial that they can work with. So if the control is dropped into a left column:

    .left .testimonial { /* some css properties */ }
    

    or if it is dropped via a shortcode into a main body of text

    .content .testimonial { /* some different properties */ }
    

    The designer can hide/show/colourise to their heart’s content without needing to come back to me asking for changes in code – “Can you add this class when you the widget is in this area?”

    What I think am getting at is I believe your ideas work great for hand crafted HTML and CSS, but take it in to the world of the CMS where the server side developer cannot know what your theme/style/css is, then things have to stay with the separation of concerns.

    0
  15. 54

    I’m always open to these changes in our architecture. Thierry, I’m wondering about a couple things:

    1. Do you have any data comparing the reduced weight in your CSS to the gained weight in your HTML?

    2. How are you seeing these, very specific, classes translate in a responsive design? When .m-10 (for example) gets changed to 5px (or 0px) of margin on a small screen, or starting your build mobile first when .w-50 may not exists? Or ever switching from a 5 column grid to a 3 column grid when going from large to small screen, the shorthand classname sorta loose meaning at that point.

    Good read, very thought-provoking. Thanks for taking the time to put this together.

    0
    • 55

      Hi Tim,

      We did a recent (internal) check regarding markup weight and we found out that ACSS lead to *less* bytes than the classic way. This is because the pages we were checking against were using very lengthy/semantic class names. And it may be the case for most sites out there. After all, to be meaningful names need to be long enough…
      As an example, the list items on *this* page contain the following classes:

      comment even thread-odd thread-alt depth-1 clearfix

      That’s a lot of characters. We could plug close to a *dozen* of ACSS classes without increasing bytes.

      Regarding RWD, please check my previous answer to Ben:
      http://coding.smashingmagazine.com/2013/10/21/challenging-css-best-practices-atomic-approach/#comment-973829

      Thanks for your feedback

      0
      • 56

        comment even thread-odd thread-alt depth-1 clearfix

        That’s not a great example.
        even, thread-odd, depth-1 can all be handled in the CSS using selector depth and nth formulas. Clearfix is a well-known hack.

        So the only really necessary classes are “comment” and “thread-alt”

        And if your semantic class names are making a noticeable impact on the size of your gzipped HTML, then you’re probably doing something wrong to begin with. At that point, why not consider a custom compiler to minify your class names? A similar approach is already used in most JS compressors; It shouldn’t be too hard to do the same thing with classes.

        0
        • 57

          …if your semantic class names are making a noticeable impact on the size of your gzipped HTML, then you’re probably doing something wrong to begin with.

          This was what I was about to say. At Yahoo’s scale it may well be that even minor reductions in code size are important, but so few of the sites on the web are at that scale that I’m unconvinced that the reduction in readability of the code is worth it.

          0
  16. 58

    Here’s the challenge I have with this concept coming from an enterprise perspective: It kills the reusability and long term maintenance of our HTML templates. If I have a “login” template that’s used across 15 sites and 4 main brands * X co-brands I can’t use this sort of class convention without it becoming non-sense very quickly. In the enterprise world products are very long lived but at the same time there’s a lot of change over time, the enterprise needs the older products to be able to be adapted visually quickly and with as little effort as possible in order to maintain the branding. This won’t work for that because not only will we have to change our style sheets but we’ll have to go back and change all of our HTML templates too and any JS that we have that might use those classes (hopefully not, but you never know with some developers). It’s simply a non-starter.

    Likewise having a bunch of coded style sheets, even if the language seems simple means teaching new developers our particular code over and over. When you’re bringing on new developers all the time, including off-shore and contingent workers this constant training (plus oversight) becomes just another added expense.

    I think the bigger problem is that many sites are put together without a design language. Someone simply looks at the page as if it were a drawing and lays things out willy-nilly, versus having a grid and rhythm and a purpose behind the design. The constant “move this over here and change this to that” is just a reflection of the lack of a cohesive strategy in design. It’s trying things out just because or because some exec doesn’t like it, versus looking at the usability and utility of the thing.

    What I’d like to see is a methodology that reinforces use of a design language, basic components using microformats, and for some presentation elements a decorator system (ala progressive enhancement). In this way our underlying HTML stays clean and reusable over a longer period of time and is more readily used in ways we don’t immediately forecast. We have a great many tools at our disposal and yet we keep coming back to the same old tired arguments of convenience and to some extent, laziness, either the laziness of our developers or that of our designers or both in that they don’t want to talk to one another to compromise on a solution.

    0
    • 59

      I *totally* agree with you saying that “the bigger problem is that many sites are put together without a design language.”

      But we cannot ignore the issues that result of this. As engineers, we can’t really tackle that problem, but we can try to minimize its consequences by reducing bloat, etc.

      Thanks for your feedback

      0
    • 60

      Great point Michael. I too want to see a better process around developing and maintaining a consistent site design language.

      0
  17. 61

    I do understand what’s the point of this technique and it makes a lot of sense in cases like Yahoo’s pages, but in my experience, I still prefer good semantics and less classes in the markup. It can get really confusing and hard to work with when you have 5+ classes in one single element. I’ve seen some markup with similar approach and got really confused. I’ve wasted more time trying to understand what was happening than doing the actual work.

    If you don’t know very well how the stylesheet has being built, it’ll like hell to style it. In a big company it’ll be no problem, but when you have to share the code with lots of different persons with different methods it’ll be impracticable. It can work pretty well in frameworks too and would make sense.

    Also to be so dependent of the markup can be a real problem. I prefer a well thought markup where you can change the most in just CSS over have to change my markup every time I have to make changes to the pages.

    0
  18. 62

    Really interesting article. I’ve been building a standardized “core” style sheet that can be easily translated to other sites for some time now. This really takes it to the next level but I feel like there’s a lot of trade offs, especially when dealing with responsive layouts and making style sheets easy to understand for other developers/designers.

    0
  19. 63

    Sorry, can’t buy this.
    It sounds like a nightmare to maintain, reuse and update. You’re styling a .button component, not .M-10, .B-5, .TAC component.

    0
    • 64

      I’m going to second your thought. It not makes any sense to break the separation between CSS and HTML, maintainance of code now it will be in HTML or views side instead of CSS, and that results in an more exhaustive labor if you want to add a simple property not included in your “library” of generic styles.

      I don’t like this idea, I understand is good for certain measures I have done it myself for generic cases, but not for rule your website.

      0
    • 65

      This is a very good point.

      0
    • 66

      No, we don’t style a button like this.
      We do have a .button class. There is a section in this article called: “No More .button Class?”. Check it out!

      0
      • 67

        This approach is basicaly inline styles as abbreviations. This goes completely against the idea of stylesheet. It has no use for small and medium projects, and for app design, if you’re eager to improve development time, use frameworks?

        Other thing is that if you develop in let’s say MVC pattern, then often you don’t want to alter the page templates, this is what stylesheets are for!

        0
  20. 68

    I’m all for considering new approaches, and I can definitely see the benefits of this in the examples you provided. I actually use the technique a bit myself.

    This gets kind of hairy when you are trying to build a responsive website, though, right? What if you need .M-10 to become .M-5 for all widths less than 640px, for example?

    To address this in my CSS starter framework Cardinal (http://cardinalcss.com), I try using .lap-* and .desk-* classes at specified breakpoints for some of my more generic helper classes (eg. .font_small, .lap-font_large, .desk-font_xl). I’d love to hear any thoughts on this approach.

    0
  21. 69

    I was just having this disagreement with a ‘new guy’ on my team. I think there IS a time and place for this type of coding but the bottom line comes down to the framework & methods of your entire product. What’s been presented here is handy if you have a basic style sheet that holds all of your usual styles in appropriate class names and every new page or article needs something coded a little differently and the HTML is available to do so.

    However, where I work now and where I’d come from previously, this was not the case. The HTML is portable – meaning it comes in modules that need to change, in some cases DRAMATICALLY in appearance, depending on which URL they display. What this means is that where one page/site would use a 10px margin, another would use 15px. Where one page has a form floating left, another page has the same form floating right. For cosmetics, the HTML is not available to edit. Classes cannot be haphazardly added/removed/edited within the HTML blocks.

    Also, design changes are frequent. The user experience is being CONSTANTLY tweaked. It is a faster process in such a large company (where HTML/PHP/Functional changes require intense QA testing before reaching the Production level) to make margin, color, font & layout changes in the CSS which are instantly updated. The size & ‘bloat’ of the style sheets becomes a necessary evil in order to maintain the slender body of the HTML. However I believe this is where SCSS and other preprocessors come in.

    I’d be interested to see some stats on the performance of an overall site that uses this alternative and how often the HTML is updated due to design changes over time.

    0
  22. 70

    What you are forgetting Thierry is that classes are also used for adding behavior to things, so jQuery code like

    $('.button').on('click', function() { /* do something */ });
    

    is very common. The reason is simple, layout and behavior are not totally orthogonal.

    So what you would have to do in your example is to add additional classes or attributes that you could use for selectors like this to be able to attach behavior.

    Now if you do this, you overcome the second concern with this technique – readability. When you simply have a bunch of style attributes applied to an element, it does not tell you what that element IS. So once again, even if you do not want to attach behavior to it, you have to add some sort of or comments to inform the reader of the HTML what it is they are looking at. In my experience, this will often be forgotten and the end result is very, very unreadable code.

    So for all of its downfalls, SoC seems better.

    0
    • 71

      I’m not sure using the same class for presentation AND behavior is a good idea.
      Isn’t one of the reasons many libraries use classes meant to be nothing more than JS hooks?
      Also, nowadays, most of the JS logic belongs to data- attributes, not to @class

      0
      • 72

        Er, the philosophy of same classes for presentation and behavior is at the heart of Web Components, which crystallizes the elegance of semantic naming.

        0
        • 73

          Javascript specific classes reduce the risk of breaking javascript if any thematic or structural change happens to web components. Nicolas Gallagher wrote about this in “About HTML semantics and front-end architecture”. He said he likes to prefix his hooks with a “.js-” prefix. This makes a lot of sense to me.

          0
  23. 74

    I agree about the short class naming as long as the developer can ensure that the class will not have different value when the redesign process happens in the future. But breaking them down into the smallest element is not good too in my opinion. Except for this case, for example:

    .tooltip {}
    .tooltip.t {}
    .tooltip.r {}
    .tooltip.b {}
    .tooltip.l {}
    .tooltip.t.r {}
    .tooltip.t.l {}
    .tooltip.b.r {}
    .tooltip.b.l {}

    0
  24. 75

    I use a lot of this when ‘designing in the browser’. Not for performance but for a speeder workflow. However the idea of it being implemented in the final build makes me feel uncomfortable.

    0
  25. 76

    I agree with the overall methodology, however, “M-10″ is poorly named because you’ve embedded a magic number in your class name. Is “M-10″ a large margin for your design, or is it rather small? How would you know? What if you need to change this later on? I find it better, and this also trims the stylesheet and keeps your design more consistent, to use relative sizes, like “m-sm”, “m-lg”, etc. No more magic numbers, and you get a sense of scale.

    I also find that you should keep refactoring your classes if you find repeating patterns. If it’s just on one page, you could use a mixin or include in the HTML template. But if it’s across multiple pages, I would create a new class.

    0
    • 77

      M-10 is *not* a magic number, it is mapped to 10px.
      It is not meant to change. If authors want to increase the gap, they do not open the styles sheet and change that value, they go to the template and change the class itself.

      We do use the approach you suggest for *font-size*, but it turns out to be of very little value.

      As a side note, it seems many commenters are missing the fact that with this technique we are switching *contexts*. To change the styling of an element, we do not edit a styles sheet, but a HTML template.

      0
      • 78

        Are you saying then that you have a m-1, m-2, m-3… m-10… m-20… m-25, p-5… p-10… p-blah-blah-blah in your style sheets? So the developer just has to go into x number of templates and switch m-10 to m-20? Doesn’t that just lead to the same problems of the HTML and CSS bloating over time and having to do extra maintenance to keep everything cleaned up? To me this all seems directed toward very short term gains versus long term maintainability and reuse. As soon as the brand needs change you have to affect a wide range of resources to realize that change. Versus focusing on a more narrow set of changes. Again it speaks to not having a solid and consistent design language and every feature/page being allowed to be treated as a potential one-off design-wise.

        0
      • 79

        Let me rephrase: 10px does not impart much meaning in the context of the design. Using a wide range of classes like this, you start designing in the HTML because you aren’t restricted to a small set of rules that reinforce the design. Also, it’s less cognitive load; in my current project for bottom margins, I have .push-xs, .push-sm, .push, .push-lg, .push-xl, which is less for me to think about than 10px vs 15px. These abstract classes also encapsulate vertical rhythm. If I want to change what “push” means, I can edit the rule and have the margins will change consistently across the site.

        > We do use the approach you suggest for *font-size*, but it turns out to be of very little value.

        Why is there very little value? Again, doesn’t this lead to “designing in the HTML”? Perhaps I misunderstood your use case, but the site’s style guide should define a limited set of font sizes. This is one of the tenets of OOCSS.

        0
      • 80

        The concern is that “A” template is rarely the problem. In situations where you’ve got a style sheet controlling A template, it’s fine: trading editing one doc for editing another. Few people would have a strong argument against it.

        I think the more common case for most of the commenters here is that your [small number] style sheets are controlling your [large number] templates, in which case this is terrifying.

        0
        • 81

          Another thing in this approach, it missleads to which units are used for sizing, ems, % or px – and using them in names makes it just to messy

          0
        • 82

          “I think the more common case for most of the commenters here is that your [small number] style sheets are controlling your [large number] templates, in which case this is terrifying.”

          That’s definitely the case if you’re building a large application (like my.yahoo.com) with a set of modular styles reused across the app.

          0
  26. 83

    As usual with things like these I try to look for a middle ground. Going all out with either of these approaches is not good. For example, if I find myself having to create large groups of selectors I would usually opt for creating a single class with the need properties and add it to the HTML. On the other hand M-1, M-2, M-3, etc.? Ugh – that is just all sorts of ugly.

    I really don’t like inline elements but it’s not because it’s the current common wisdom or something, rather I just would prefer not having to edit two files if I wanted to change the look of something. Having to replace Mend-10 with Mend-20 and then also go into the CSS and update a styles doesn’t seem all that efficient.

    In any case, like mentioned above, I typically end up with both approaches in my projects, and depending on the project I may favour one over the other.

    0
    • 84

      “Having to replace Mend-10 with Mend-20 and then also go into the CSS and update a styles doesn’t seem all that efficient.”

      This is the whole point of this technique is that you would only need to replace Mend-10 with Mend-20, there would be *no need* to touch the styles sheet.

      0
      • 85

        This assumes a strong CMS is in use to be able to make site-wide changes to HTML quickly. One of the advantages of Stylesheets is that you make the change once in the .CSS rather than multiple times in the HTML markup across multiple pages – I don’t see why you would want to throw away that advantage.

        The solution to most CSS bloat problems is to step back and write better CSS in the first place, not “pollute the markup rather than the style sheet”. I don’t know if that was just bad choice of words by the author, but it implies you have bad code and you’re moving the problem around rather than fixing it.

        0
  27. 86

    Benjamin Gandhi-Shepard

    October 21, 2013 6:55 am

    Isn’t this just OOCSS basics? I’m happy to see this catching on.

    0
  28. 87

    I use CSS so that I can change a thing on one place. Your approach seems to have it so that I need to change the markup every time I need to make an adjustment.

    Currently I am involved in a very big project building a newspaper online.
    I use less and have a grid system that make use of variables like @columns, @gutterWidth and @columnWidth.
    The class for making a column is simply col1, col2 etc. This way I can simply change number of columns and column width in the _variables.less without touching anything else.
    This takes one minute at most.
    Would you suggest I make a col250, col275 etc. for each width I would predict to use in the future? And then change the markup where these exists?

    I’m thinking what you describe is what I use as helper classes. An example would be “.right” or “.left” to make an element float right or left.

    Maybe I am missing something, I’m always looking for better ways.

    0
    • 88

      We do have a styles sheet for layout. Mostly because values we are using in there would not have much value outside of that scope.
      This technique is not about using “helper” classes for *everything*, but using them when it makes the most sense.
      Check http://my.yahoo.com, you’ll see that we use both techniques to achieve the styling of the page and its modules.

      0
  29. 89

    Christian Montoya

    October 21, 2013 7:06 am

    This is not an entirely unique idea. CSS frameworks like Blueprint & 960gs pioneered this with their modular & reusable rulesets. It wasn’t a popular idea at first but judging by the success of these frameworks, it’s popular enough now :)

    Obviously different horses for different courses… sometimes it’s best to have rules be very context-based, sometimes it’s best to be very modular. It’s up to the people doing the work to decide what’s best.

    0
  30. 90

    I must admit I find this technique horrible, but I am willing to admit that there are places where it makes a lot of sense. Web apps can certainly benefit from this, but “ordinary” websites for individuals or small businesses, where the people maintaining it have minimal training or interest, well, this just isn’t going to be useful.

    In these cases, you simply can’t expect users to worry about classes. It’s hard enough getting them to use html elements correctly through their CMS. Tell them they’ve got to start adding all these classes? You’re wasting your time.

    0
    • 91

      I agree that there is a time and a place for this technique as with any other. For me it boils down to making the right decision for the project at hand. I will be making different decisions working solo on a small site than I would on a large site. And when working with a team decisions may be based on the project or what works best for team as a whole.

      And just to recap your final note:

      “We all need to be open to new learnings, new approaches, new best practices and we need to be able to share them.”

      0
  31. 92

    [data-nav] { Shared }
    [data-nav="primary"] { Specific }
    [data-nav="secondary"] { Specific }

    0
  32. 93

    Good article.

    It strikes me that many of us are already, sometimes inadvertently, adopting this approach by using various frameworks, or, at the very least, a grid.

    The struggle to shirk off the semantic mistakes of the past is a tough one – .sidebar , .topnav, .block, .footer – they do little other than ‘box’ your content into pre-defined semantically named areas. Your tied to them.
    Responsive layouts have led us to question the logic of applying such broad strokes to our CSS – a side column is no longer a side column when you only have one column!

    By pushing our semantics into HTML, by the correct usage of section, aside, heading, footer, we no longer need them in CSS, except to describe much smaller brush strokes.

    I’m not sure I’d go so far as the concepts described here – to take it right down to classes for a specific margin width? – that strikes me as veering dangerously toward having to directly edit HTML structure instead of stylesheets.

    If you’ve slapped a class of .M-10 into an HTML tag and decide that actually, you want a 20 pixel margin… hmm, and hold on, you want to apply that across the board – and you have numerous template snippets to search through.

    Take a look at your div example:

    Fl-start Mend-10 W-25

    That’s *really* specific when it comes down to it – you’ll have no choice but to edit the HTML if you want to change that specificity.

    I like the concepts, but definitely would prefer to stick to a more modular approach that doesn’t describe margins, widths or padding in the class names themselves – that’s why we have variables, mixins etc. in sass / less.

    0
    • 94

      Well-said, Matthew.

      To extend your points, I’d like to add that the amount of esoteric knowledge required to even write the html in the first-place is way too high. CSS frameworks usually have a great documentation resource centered around a few handfuls of these things – a grid system is a great example : “span6″ or “six columns”, etc.

      It’s fine for something as central as page layout, but getting into individual element layout and every single CSS property (underline-1, bold, margin-12, margin-top, etc etc.) is exhausting, to say the least.

      I don’t care how awesome your selector performance is, or how compact your html may be, having to know when to use class names called :”Bfc M-10 Fl-start Mend-10 Bfc Fz-s” makes me cringe. And that’s just from your first example.

      I applaud the Author for being so bold to recommend such an approach, but I think it’s taken too far to the point of impracticality; even a step in the wrong direction. Instead, let’s take the good parts and mix them with the current, modular approach where it makes sense.

      A relevant question could be, “when is it a good idea to modify content for styles sake”? Grid / layout systems come to mind, or when the element itself changes function. So it would make sense to add a class to : Help! called “alert” or “warning” if the function of that button changes to warrant a class addition.

      0
      • 95

        After writing my comment, I was considering that the approach the article aims itself toward is, in a way, tipping everything on it’s head. You pre-define a set of core CSS styles and edit the HTML to match. I’m sure that’s not the intention, but it sort of reads that way.

        It’s almost as if we’d be throwing away the ‘cascade’, such is the base level simplicity implied.

        The way I see it, you put together a bunch of modular re-usable CSS styles – blocks, panels, navs – and use the cascade for specific targeting.

        .panel { … base styles … }
        .module-name .panel { … specific styling …}

        Heck, you can tap right into role, or data attributes rather than class attributes and cascade down that way. You’ll still end up with a minimal amount of classes, but will have the benefit of keeping your HTML lean and mean, rather than littering it with specific CSS classes.

        We also get down to the correct use of HTML tags – the example HTML at the top of the article for instance, with .media as the parent – there isn’t actually any need for any more classes in that.

        0
    • 96

      This is the part of the article that I think many people *missed*:

      “But the most important thing to notice here is that we are styling via markup. We have changed the context in which we style our modules. We are now editing HTML templates instead of style sheets.”

      To understand the interest of this technique, you need to leave behind the concept of styling everything through styles sheets. If your workflow does not allow you to easily make changes in the markup, then forget about this approach :)

      0
      • 97

        Hi Thierry – I actually got the gist after my initial comment, see my reply just above yours. It’s an interesting method, but perhaps the examples are what throws confusion into the mix.
        I could see this method working well across a suite of sites which all require design continuity, but the question does remain just how far you take the concept, until you reach a point where applying a redesign requires numerous changes across your template code.

        Arguably, if your architecture is neat – and modern – the ‘views’, in whatever templating language, should be easily modifiable.

        Clearly it’s worked well for you, but after looking at the source of My Yahoo, the markup is … hideous, there’s no identifiable sections, headings etc., virtually every html tag has numerous classes on it, it fails validation quite badly and looks as if it wouldn’t be very accessible.

        0
        • 98

          “there is no identifiable sections, headings etc., virtually every html tag has numerous classes on it, it fails validation quite badly and looks as if it wouldn’t be very accessible.”

          We support IE, starting with IE6, so we do not use <section> and other HTML5 elements, but we use WAI-ARIA @role to identify blocks. What make you think it is not accessible? It is built with accessibility in mind, so please let me know if you find we missed something.

          Thanks for the heads up regarding validation. Those errors are not related to the technique discussed here, but still, we should not have those :(

          0
      • 99

        No, we get it, but for those of us that have been in the industry a long time (pre-css days) this defeats the entire point of what CSS is meant to do, and completely throws away the cascading power. If I’m going to have inline styles handled in HTML, then I may as well go all the way, move everything inline and drop the extra request the CSS files.

        Long term maintainability of this method sucks. Very few content platforms are so tightly controlled and regulated that you have the power to globally update every m10 to a m20 when designs change.

        0
      • 100

        well, then please change the headline for this article to stop polarization :-/

        guess for the most devs it reads like “break up all of your code in smallest pieces” without getting any idea WHY. Of course it does not make sense to most devs to create stupid classes that hold 1 property. Actually it really is silly if you’re not in the context of having multiple sites sharing some modules.

        basically I’m on the “haters” side as it appears to me not to make any sense in regular web presentations:
        * HTML bloated (in fact this is inline styling)
        * you get a headache viewing the code (i really tried at my.yahoo.com!)
        * it does NOT have to do anything with responsive stuff: m10 should remain a margin of 10px in every device, that is what the class is for

        I’m a fan of abstracting page components and specification through semantic classes.

        0
  33. 101

    I’m not sure I see how having 10 different classes on a single element in your markup is any different than having just one and being overly specific in you CSS. You’re simply moving the bloat from one place (your stylesheet) to another (your markup).

    I think there’s a happy medium here. While I think Bootstrap as a framework is a bit bloated, using base and extender classes (ex. .btn, .btn-primary, and .btn-large) allows you work in a modular fashion and reuse your classes without needing to completely tear apart your markup if you change your design direction in a year.

    OOCSS is great, but let’s be pragmatic about it.

    0
  34. 102

    Definitely good to think outside the box and challenge the rules. But, in my opinion, all you are doing is moving your style changes to your markup from your CSS.

    In Zen Garden’s approach – the same markup can be styled a zillion different ways by changing the style sheet. In your approach, a single style sheet can be used to style virtually unlimited markup (so long as the markup has been written with the specific stylesheet in mind).

    Overall, I think the method presented in this article encourages enormous base, reset-style (have people yet figured out that they don’t need normalize.css?) CSS that will ultimately lead to CSS bloat.

    0
    • 103

      “Overall, I think the method presented in this article encourages enormous base, reset-style”.

      Actually, this is not our experience. Did you check the comparison table we have in this article? It shows we can produce many more variations with much less KB.

      0
      • 104

        Please stop using that table as “proof”. It’s an apples-to-oranges comparison.

        You’re comparing the results of a newly architected design to completely different designs on different properties with different needs.

        If you want to be honest about it, show a traditional approach vs. your approach on two best-case implementations of the same design.

        1
  35. 105

    I agree that we area at a point where we need best practices for CSS, Responsive and large applications are requiring us to use modularity and reusability and careful commenting and organization to keep these files optimized, maintainable and what I might argue with what you have recommended is readable to the future developers.
    I came to a similar practice in one of my earliest Responsive redesign projects, where I was using OOCSS techniques (which dramatically increased my productivity in writing code, I too used some of SMAC ideas) and saw I was creating different modules that could be reusable and then began refactoring and modifying using new classes for resolution type behavior.
    What still has not been resolved for me, is how to organize these modules, elements and behaviors with classes and more importantly how to communicate to the team how the framework is built. It took some explaining to my team that some classes would be in the html and not do anything until a resolution was hit. Early I used a lot of single parent classes that told the child elements how to behave, but when backend developers added something else into the dom area, they would not understand why they would get a certain behavior. As I said the biggest challenge was when I left that company and had to write out a large document explaining where to find what, what purposes some classes presented, and how the whole project was organized for who might take over the project.
    That’s where I worry your organization is difficult to understand for the next developer, yes they can eventually memorize a lot of reusable classes, but where do they look to learn, where do they know to put things, how when looking at the Html can they understand and our partnered back-enders know purposes of these classes (Especially when Sass makes it hard to debug our css).
    Which brings me to the best method I have seen to resolve this issue, the BEM methology. I agree with the criticism that it is ugly, but I think now that we are using so many style sheets, so much modularity, and again we are adding a lot of classes markup into the HTML, how do we communicate their purpose. I’m playing with different ways to write the block, element, modifier idea, it might be a combination of BEM and what you have (the second class may be for the modifier options.)
    What I do appreciate is the conversation of ideas for organizing CSS and the community sharing. If I finally come up with something solid, I will share too. Thanks.

    0
  36. 106

    I do a similar thing where I take advantage of short cuts and combine it with standard practices. In your media example, I’d still use the media box, but any of the margin or padding would be “ml10″ or “mr10″ and floats “rlri” or “flle” . As I carry on, I do have to remove short cuts if there are variations in layouts, but I find they make my life easier. I find using the combination saves file size.

    0
  37. 107

    Whether this works and whether this is good practice are separate things. This is a system, and it can work, but that is not saying much. This will make high-level reasoning about the page much more difficult.

    The problem of specificity is real, but the solution is not to throw away the basic logic governing the relationships between DOM and DOM consumers. Those “Tips for Webmasters” (which we must remember are merely tips and lack any of the credibility and discipline of the actual Recommendations) actually indicates, in the H2 tag of that page, that one should “Use class with semantics in mind.” How anyone can argue that this document is not about semantics is beyond me.

    One of the most practical things that comes from semantic class naming is that *multiple* template artifacts can easily re-use the same family of semantic classes. Say you have a client-side Jade template that renders a media object, and you have an equivalent server-side ERB template. If this is implemented with “atomic” classes, the implementation becomes very fragile and those “atomic” class names must be carefully synchronized between ERB and Jade in order to maintain consistency as the design evolves. With semantic classes, synchronization is only necessitated when structural changes occur.

    Another problem is that this “atomic” philosophy has absurd implications when applied to behavioral needs. Does one add a separate “atomic” class name for every discrete behavior that a web component needs? Of course not. Semantic hooks are just as beneficial and easy to reason about when it comes to behavior as presentation.

    So how is the specificity problem solved? There are many ways, but I am a strong advocate of using the child combinator (>), as I explained here http://www.scrambledbrains.net/2013/05/28/more-on-modular-css/ . This applies both to presentation and behavior (Sizzle/jQuery and native DOM methods have long recognized the child combinator). Feel free to trek off into the wilderness and risk your own projects with complicated solutions that reject extensively considered architectural frameworks and recommendations; just don’t imply it’s a best practice.

    0
  38. 110

    I very much agree with this post. In fact I’ve posted a css “mini-framework” called DeputyCss that includes a ton of helper css classes very much like those described here.

    Here is a link to the github project http://ry4nolson.github.io/Deputy/

    0
    • 111

      I’m one of the guys on the team with Ryan that built deputy. I think its important to mention that using what we call helper CSS classes on a project that will ultimately be maintained by a client that is less than code savy can make for big wins for that client. Their able to replicate and expand sections of their site without having to have deep understanding of what is happening.

      0
      • 112

        Ryan, Adam,

        I just checked “Deputy”, it does look a lot like Atomic.css. :)

        “They’re able to replicate and expand sections of their site without having to have deep understanding of what is happening.”

        Totally agree. And it goes the same with devs. Devs can copy/paste modules to get them started… No need to start everything from scratch. And as this article suggests, one can copy a template used to style a “media object” and use it to create a 2 column layout. That’s because we don’t have “semantic class names” attached to the template that would prevent us from re-using it for a different purpose.

        Thank you for your feedback and for letting me know about Deputy

        0
    • 113

      i reject this kind of extensive usage of !important. its just contra-productive (!important)

      0
  39. 114

    My first thought was “OMG, inline-styling all over again”. But since I really do love my job, I like learning new thinks, that challenge me and show me new approaches and ways to do stuff.
    Let me try to put my thoughts into a list

    1. It really is a bit like inline-styling
    2. It bloats the html, which might be less of a pain but I think, thats personal taste
    3. It makes modules really independent
    4. I’d like to have some “real” data – like one (small) website coded in this and in another way
    5. There is a reason for @media… and I don’t think, this would work to good with media queries

    Now let me explain a bit more:
    1. Since many styles are getting their own class name, it’s not that different. There is really no difference between style=”margin-right:10px;width:100px;” and class=”Mr10 W100″ now, is there? Of course, this way breaks classes down to the most elemental pieces (atomic design ftw) but why use classes at all, if every class only hold one property…
    2. I mostly work with smarty-templates within a ecommerce-system called shopware. These templates are bloated and stuffed with placeholders by default. If I’d add all those single-/double-property classes to my elements, no one could ever maintain those templates again ;) Of course, if you write all you code by yourself, there’s no real harm there. Still, I think it’s a question of personal taste.
    3. This got me thinking. Even though, all these classes would bloat my html and clean my CSS, the biggest benefit would come from developing new modules in no-time. It’s so good to just add code to one file (HTML) and the module looks good from the beginning because it seamlessly works in your context, whatever it may be.
    4. Do you have any example?
    5. Many before me commented on this. Responsive design happens in the CSS. HTML contains the content with its markup (duh) which should stay the same, so why change anything in here. But if you use @media, then the classes would either lose their meaning (.border4px having a 2px border) or don’t change, if the element doesn’t change.

    What you described above is used in many frameworks. And why not? I mean, that’s what frameworks do. They give you modular classes, which hold the (in their opinion) most common propertygroups so they can be reused whereever needed.
    My favorite part of this your post was the end (not, because it was finally over ;) ). Tools, not rules! Neither your way nor any other way is “the” way (as you mentioned in a comment above). I (for example) think, that HTML needs classes like .calendar or .contact-box because this is the most recognizable way for us humans to see, where those styles belong to. That doesn’t mean, that I can’t use classes like .M10 or .Fl too. Every time I learn something new, I try to find a way to take the best of what I learned and merge it into my workflow. Everything has its place and should not be overused. (I want to throw in this: http://css-tricks.com/dont-overthink-it-grids/).

    Oh, one more thing:
    It sounded a bit like you don’t like preprocessors. Personally, I use Sass/Compass to automate many things in my styles (spriting in compass rocks!), the @extend directive is really awesome. But one thing I’d like to add here: Preprocessors don’t write bad code, coders write bad code ;)

    Thanks for your article, opened my eyes to a new way :)

    0
  40. 116

    I really don’t agree with this at all. You’ve got to go in and change your HTML whenever you want to modify a design. This is craziness, especially if you want to design responsively. What if you want “W-50″ for desktop, but on mobile, you want a width of 100%? In theory, you’d have to change the class to “W-100.” Or you’d have to add a responsive condition and make “W-50″ width 100% … which doesn’t even make sense.

    0
  41. 117

    While I agree that smaller, reusable chunks of CSS is a step in the right direction, your class names are still something left to be desired. You correctly point out that they’re “cryptic”, and without a solid pattern backing class and ID names, it will remain so. You devote only 2 sentences to explaining the pattern despite it being the crux of the article.

    I think this type of approach would work great for sites that use and abide by a styleguide or template (a la Bootstrap), but we all know not all sites do. Thus, having redundant class names like .M-7, .M-8, .M-9, etc. is exactly that — superfluous. Relying on gzip, although a good practice, shouldn’t be the end-all solution. Perhaps it’s just laziness (we’re developers, after all), but I would personally prefer to see a singular location for all styles related to an element, rather than piecemeal chunks defined by hundreds of classes.

    Lastly, given the long-standing history and prevalence of SoC, there would definitely be an uphill battle with regards to adopting something such as what’s proposed here.

    P.S. Why is the comment box at the bottom of the page? Being forced to scroll past every comment sucks — poor UX decision IMHO.

    Edit #1: Typo

    0
  42. 119

    Editors Note “coding techniques that we are used to today”

    0
  43. 120

    I don’t agree with your technique 100%, but for the most part, yes I agree. And I applaude you for having the guts to say a few things many others think but prefer not to start a war on their porch overit. SoC is solid and sound, but that doesn’t mean it’s bulletproof. Any rule will eventually see its exception.

    Personally, I stick with SoC because it’s convenient and it saves time (both mine and my collaborators’), not because anyone else thinks it’s law. In my rulebook, “it has to makes sense” and “don’t be anal” are way higher then “do what’s considered best practice among bloggers”. So when it’s no longer convenient or it makes us waste time trying to figure out, I step on the rule, a little….

    However the extent to which you push things make me cringe a little. Still, if you save time, need less ressources, and manage to work in team with these guidelines without strangling each others, it’s a pretty good sign that it works.

    Personally, I always keep a bunch of “dirty” classes like txt1 to 5 for text sizes. However, these include several other attributes (line height, weight, font, margins… Anything related to the what tiny to huge text needs). And several decorations that pop often: box, lightbox, border1 to 5, several txthl for highlighted texts, several background colors (mute, tint, boxhl, accent). I’ve found throught some mistakes that it’s optimal in terms of reusability if I:

    1. Don’t make single declaration classes, but regroup what makes sense (ie not just a backgroud color class, because the text color is concerned as well, and the border color as well).

    2. Use names that describe accurately what the classes does, but not in a restrictive way. That way it doesn’t get to the weird awkward point where you have to remember that the class “orange” is now blue. I prefer to have classes like split2 instead of col450, I also prefer to have background color classes that still work even if the palette changes drastically. Instead of btn-red I ‘d use btn-negative (negative, in a context where a red button would be used for negative actions, like ban, delete, because in a red palette it probably wont’ be red) , and instead of bg-dark I prefer bg-contrast (I had to change a website’s palette from dark text on light background, to light text on dark background. Collaborator was confused as why bg-light was darker then bg-dark. Awkward.

    3. Stick more closely to SoC for general stuff, like the main template blocks, menus, and such. The main benefit of styling classes is for smaller reusable elements like subheaders, paragraphs,

    Anyway, that’s what work for the kind of project we do at work, where we need to assemble new sections for existing websites quickly, have to handle several color themes, have to reuse internally, and also need to keep the same corporate identity accross several webapps. It might not work for other types of projects, like whatever gets handed to novices for updates and maintenance, like someone mentionned.

    0
  44. 121

    I can relate to many commenters in the initial gut reaction of saying “woah, crazy now!”.

    I then re-read the article.

    What i’ve noticed is:
    - many people didn’t actually read the article, or rather comprehend what they were reading.
    - many people are too wound up in the newer trends to open themselves up to this type of concept and worflow.
    - some people are just haters.
    - none of the people who commented have worked in a systemic environment which utilizes in depth practices such as this.

    My experience comes from systems and practices such as this, large scale corporate environments.
    There was always up to date documentation, and yes the onboarding of new hires took time investment, but the long term health of any of the 22 sites running on this system was the end goal.

    I still use a lot of the methodologies brought up here, albeit not so in depth, and applaud bringing it up.
    Hopefully more people can open their minds a little more.

    0
    • 122

      I’m glad to see there are people out there who notice these things…
      Thanks rory for your comment!

      0
  45. 123

    I think it would be better to combine ideas. I’d like to keep my #sidebar and #footer IDs and such, if only to target them via @media for responsive layouts and hiding things for printing. From there, follow your idea about everything else. Basically, ID’s for major block positioning and Emmet style classes for everything else.

    0
    • 124

      This is about “combining ideas”. As the article says, we are not banning semantic class names, we even show examples such as “Button” and “Modal”.
      I don’t understand why people think it should be one way or the other…

      0
      • 125

        I guess something like the out-of-the-box “96″ reply number here on this site wouldn’t have happened with the proposed system. Just because it’s not overriding an existing style but choosing from different predefined classes that do not interfere too much with each other, right? (Btw. same things happens also to reply number 85 in my FF on XP).

        0
  46. 127

    This does blow my mind and it’s a very interesting approach to have developers write consistent and maintainable styles

    Looking forward to seeing some tools which can generate a limited set of rules (like the stencil in my yahoo)

    0
  47. 128

    This has merit, though from RWD experience often you need to use a different set for different areas such as .header div{ font-family:Arial; } to .content div{ font-family:sans; }

    The biggest problem though is when you are editing a template that contains blocks spread out over a number of files, it can be praticulay hard to say increase .gridspan7 to .gridspan8 without breaking the layout as you then have to change something some where else where as .mycustomcss { width:80% } will do just fine if your working for money.

    Also no one has mention the helpful * { color:foo; } “whiled-card” that will just to anything to everything

    0
  48. 130

    “I hear you saying, “This goes against every single rule in the book. This is no better than inline styling.””

    Because it is.

    I love when people put a tremendous effort into reinventing some—more or less—working paradigm/principle/etc. (CSS in this case) just to find some new, almost perfect and a long lasting approach.

    These people often forget two things.

    1) Their brand new solutions are just _almost_ perfect too—i.e. those who invented them know their drawbacks, but the rest of us have to learn them. Way better if I stick to my own half-perfect, but proven workflow with my already known bugs, I’d say. (Read more about this on Joel Spolsky’s blog, where he explains why it is a total disaster when a product is “redesigned from scratch” vs. the good old tracked-bug-new-version approach.)

    2) Their brand new solutions target the “eternal solution” that would last forever—or at least until the next CSS version/Chrome feature introduced/mobile or tablet device put on market next Christmas. Which comes earlier than the Developer World would switch to and attain a whole new design pattern.

    I’d say: just easy, boy. Always decide, what’s important. I think code maintainibility and readability is much more a crucial question if it comes to practice.

    0
  49. 131

    Isn’t ACSS essentially going down the same sort of route as Sass mixins?

    Whether setting a $border-color mixin or a simple .bc class, the way of thinking is much the same.

    As a team of six at work, we have a set of ACSS classes we use in all our projects, in their own stand-alone CSS file: .cb (clear:both), .fl (float:left), .p-10 (padding: 10px), .m-5 (margin: 5px), etc. that we all instantly understand and remember, and use within our projects. It saves considerable amount of time, and as we all know what the classes mean, it effectively *is* semantic…

    0
  50. 132

    Thierry, I definitely fought this new approach as I started reading. Why not just write inline styles then? and how about defining ALL the CSS properties as class names and bloating the heck out of your HTML? were two of the sarcastic thoughts that went through my head. Then I relaxed a little and tried to learn.

    I appreciate the idea of the Atomic Style Sheet or these micro-styles. I understand how they can be useful and easily re-used. I do, however, think that there is probably a “sweet spot” to be found in between DOM structure-related classes and “atomicly” styled classes.

    Readability is an important factor in “good coding” practices and sometimes it’s just easier to be able to jump to a section of the CSS that deals with a specific part of the HTML structure.

    I appreciate the article will try to utilize some of this in my larger projects.

    Thanks for the challenging read!

    0
  51. 133

    Unfortunately, the article doesn’t use any good code—it’s either bloated, presentational, inconsistent, invalid, or all of the above. Of course then, garbage in, garbage out; alas, if the premises of an argument are wrong, the conclusion is wrong too. (I pick up that Thierry, you picked third party code, but it torpedoes the very points you’re making.)

    Separation of concerns is one of the keys for maintainability. In web development, the complexity that this can add to the CSS side is very much acceptable because HTML changes are much more expensive than CSS changes.

    As for OOCSS, how did that end up here? http://meiert.com/en/blog/20130806/object-oriented-html-and-oocss/.

    0
    • 134

      Hi Jens,

      “In web development, the complexity that this can add to the CSS side is very much acceptable because HTML changes are much more expensive than CSS changes.”

      Please define “expensive”. If expensive is a cost, then I think there is more to it than comparing the time it takes to change the style of an element. It can be a snap to do it via a styles sheet, but it does not come for free:

      - adding rules creates bloat,
      - constantly editing a sheet reduces its chances to be cached,
      - styling via the styles sheet leads to poor maintenance, because nobody takes care of redundant or obsolete rules (and if they do, then it’s not much faster than managing classes in templates),
      - editing a styles sheet has a QA cost – because such changes belong to the *global scope*.

      Also, if your choice is to use “atomic” rules, then you adopt a different workflow. One that facilitates editing templates instead of styles sheets.

      But once a gain, I’m not telling people that’s what they should do. This is a something we want to share, not to “impose”.

      Thanks for your feedback

      0
  52. 137

    I couldn’t disagree more… You wrote over complicated code to make it seem daunting. I wrote the most “complex” version that you gave with and was able to slim down on your code a lot. I posted a version on codepen here: http://codepen.io/CWSites/pen/BvIHj

    The entire post is about “best practices” which combines readability and easy to manage/update. If any developer other than the one that wrote it tried to make their way through the code they would end up with a headache and more than likely do as I did and wipe your stuff out completely and start from scratch.

    0
  53. 138

    I’d like to argue the often mentioned argument that it would be too much a learning curve for new team members. It is a quite “clean” system (as in “structured”) where the background is quite easy to get. The hard part is to understand its meaning completely to actually be able to put the right classes into the right places. If the system allows discussion (which in my opinion is very limited), only then it would end up as nightmare to maintain.

    The other thing is, that most people tend to see OOCSS-focused CMS to be the best partner for this – think again perhaps. Perhaps the CMS should be more supportive for this kind of approach to actually make it more human-useable and cover some of the OO-part for this style of editing.

    0
  54. 139

    Greaty Article Thierry, very interesting approach your fingers must be tired from responding to all the comments :) . Obviously there is more than one way to skinning a cat (or website) and this is one of those techniques. Not really sure why some on here are blatantly disqualifying this technique, but I guess thats what comes with this territory lots of opinions which is a good thing … more diversity the better. This method is obviously a technique that you should apply to relative situations where you as the front-end dev will deem it necessary. If it was for a platform that is always evolving and changes its look and feel from time to time I could see it being a problem. There are number of different kinds of techniques out there and we chose wisely the approach we take on that project.

    0
  55. 140

    I can see the wisdom in this. It follows my recent new mantra: “The smart thing to do is write dumb code”

    That is, the less the code knows about itself and its context (i.e. “dumb”), the more flexible, extendable, transportable and maintainable it will be.

    Case in point: class=”sidebar” vs class=”Fl-start Mend-10 W-25″

    The first is too smart for its own good and as Thierry shows, causes all sorts of maintenance issues.

    The second, although “dumb” (since it knows nothing of its context), is more maintainable and flexible.

    The one thing I would consider though, for simple HTML readability, is to still include the contextual classes (without styling). e.g. class=”sidebar Fl-start Mend-10 W-25″

    0
    • 141

      “class=”sidebar Fl-start Mend-10 W-25″”

      You got it. This is exactly what we do. The template is built/created in relation to what it is supposed to look like. At this stage, we only have presentational class names. Then somebody pick it up (copy/paste it) to hook data. If it’s a module to display a list of items, then it may be used to show tweets and it would be called “tweets”. To present testimonials, the class “testimonials” would be added to it. That same template could be picked up by another team who’d plug a different feed into it, so they’d call it “stream”, or whatever. And so forth… In other words, the “semantic” class name comes in well after the template is created. And until then it has *not been used to style* the template. If somebody on the network see that template and wants to use it, he only has to get rid of that class name and plugs his own content. Replacing that class name by his own semantic one should not break anything.

      0
  56. 142

    Smashing Magazine invited me to respond to Jeremy Keith article (http://adactio.com/journal/6537/), so here it is:

    Jeremy says that “[I] advocate entirely presentational values”

    This is not entirely true. What I’m saying is that people should avoid using class names related to content to style their modules. This is because by doing so they limit the re-usability of the rules they create. See my example of the “media object” that cannot be re-used to create a simple 2 column layout simply because its name relates to something else.

    I also explain in comment #111 that we do (as Jeremy suggest with <div class=”media Bfc M-10″>) have semantic class names attached to modules, they are simply rarely used as hooks for styling:
    http://coding.smashingmagazine.com/2013/10/21/challenging-css-best-practices-atomic-approach/#comment-974117

    Anyway, “adopting” atomic.css does not mean one needs to go full “presentational”. Authors can create their own atomic.css file including whatever rules make sense to them – mixing both approaches:
    http://coding.smashingmagazine.com/2013/10/21/challenging-css-best-practices-atomic-approach/#comment-974051

    0
  57. 143

    Hello Thierry Koblentz, how are you?

    This article inserts a basic idea of OOCSS, I am a great apologist this technique.

    OOCSS combined with Atomic Design (Bread Foster) is essential for modern workflows and scalable projects.

    But… I have to disagree of way they are use. You are building a “locked” code.

    For example… you defined:

    “.M-10 {
    margin: 10px;
    }”

    But… if margin is changed for 20px? The name of classe continues with M-10 or you will need change the name in all HTMLs.

    Set the class names for the function, never for the attribute.

    Also I disagree of use this great number of classes for create the elements, this way you have the same problems that existed before of CSS use.

    Not is necessary create extremely generic classes, just create of the required components.

    0
  58. 145

    I’d say about my opinion. If a type of element were used many times (e.g. the “reply” link appearing after every comment in one page), with about or exactly the same style, I think it fine to extract a “.reply-link” (or the like) class for it. But not if it just appeared once and share some styles with another element and some others with even another. That’s time to use presentational classes.

    0
  59. 146

    Another interesting article that I happen to agree more with: http://www.kapowaz.net/articles/cargo-cult-css

    0
  60. 147

    This would never work in an agency environment. I won’t be adopting it as I’m usually in an environment where each page has it’s own custom design.

    I can see limited advantages if you are working on a core product, but even then it’s still no different to writing inline css theres no time saving here you’ve just reshuffled the bloat.

    0
  61. 148

    Using this technique would require a lot of HTML to be rewritten to restyle a site.
    It makes any responsive implementation difficult, and renders class names meaningless.
    It make it difficult to provide alternate themes, and prevent users from injecting their own styles.

    It’s a horrible, lazy, restrictive, short sighted way to define styles.

    0
    • 149

      Hi Jake,

      “Using this technique would require a lot of HTML to be rewritten to restyle a site.”

      If your choice is to use “atomic” rules, then you adopt a different workflow. One that facilitates editing templates instead of styles sheets (check comment #106)

      “It makes any responsive implementation difficult, and renders class names meaningless.”

      I do not speak about RWD in this article because it is not the core issue (atomic.css), but I do reply to the early comments/concerns:
      http://coding.smashingmagazine.com/2013/10/21/challenging-css-best-practices-atomic-approach/#comment-973829

      “It makes it difficult to provide alternate themes, and prevent users from injecting their own styles.”

      Please check http://my.yaoo.com (you’ll need to be signed-in) where we provides dozens of custom themes.

      “It’s a horrible, lazy, restrictive, short sighted way to define styles.”

      This is how you describe it? Even though the last section of the article talk about:

      Less bloat, Faster development, RTL interface for free, Better caching, Less maintenance (on the CSS side), Less abstraction, Facilitates Third-party development.

      Thanks for your feedback

      0
      • 150

        Why would you want less maintenance on the CSS side when it means more maintenance on the HTML side? And your method clearly means more development and maintenance on the HTML side.

        Faster development? I see nothing in your post that shows this offers faster development. In fact, I see little in your post that shows this method offers anything you claim.

        0
  62. 151

    As a former Senior Front-End Engineer on the My Yahoo! team and former Front-End Architect at Yahoo!, I weep openly at what has been done to a once fairly high-quality codebase.

    Your ‘What’s Wrong With This Model?’ section sets up several strawman arguments. You then set off knocking down said strawmen, doing immense damage to the future maintainability of your codebase (not to mention the sanity of your fellow developers) along the way.

    Point by point:

    > Simple changes to the style of our module have resulted in new rules in the style sheet. There must be a way to style things without always having to write more CSS rules.

    Wait, you mean to say that changing styles involves… changing styles?!

    Let me turn the second sentence around to show that your solution is no better: “there must be a better way to style things without always having to write more HTML”.

    > We are grouping selectors for common styles (.media,.bd {}). Grouping selectors, rather than using a class associated with these styles, will lead to more CSS.

    Again, turning the second sentence around: “Using a class associated with these styles, rather than semantic class names with grouped selectors, will lead to more HTML”.

    > Of our six rules, four are context-based. Rules that are context-specific are hard to maintain. Styles related to such rules are not very reusable.

    Nothing you’ve written proves that these rules are harder to maintain than HTML littered with presentational classes. This smells very much like a strawman to me.

    Styles related to such rules are /less/ reusable than one-property-per-rule presentational rules, yes. To say they’re “not very reusable” very much depends on context. It’s perfectly possible to write a reusable set of CSS rules hooked into semantic class names. This sounds more like a lack of familiarity with best practice web development than anything else.

    > RTL and LTR interfaces become complicated.

    Again, only if you’ve not written your HTML and CSS with RTL and LTR in mind.

    Then, the listed benefits of your technique in the “Wrapping up” section contains some seriously spurious claims:

    > Less bloat.
    > We can build entire modules without adding a single line to the style sheets.

    “Less bloat”, by which I take it you mean “I didn’t have to write any additional styles”, is demonstrably false. The additional styling information is still there, it’s just in your HTML and not in your CSS. In fact, if this module looks exactly like another module on the page – or on any other page – you’ve now got more bloat rather than less because you’ve duplicated the styles along with the markup.

    > Faster development
    > Styles are driven by classes that are not related to content, so we can copy and paste existing modules to get started.

    Copy and paste development really isn’t something to encourage. Copy and paste is the entry level of code reusability – everyone starts there, but you quickly learn that you’re just adding additional heads to the monster you’ll have to slay come refactor time.

    You’ll be in a much better place if you just describe your content, not what it should look like today.

    > RTL interface for free
    > Using start and end keywords makes a lot of sense. It saves us from having to write extra rules for RTL context.

    “free”, where free is something that means a heck of a lot more work embedding ‘put margin at start’ and ‘put margin at end’ class names in your HTML. I liken this selling point to Candy Crush; it’s free until you realise that you’ve spent hundreds or thousands of dollars/pounds/euros/etc in in-app purchases. By the time that realisation bites, you’re so far down the road that you have basically no other choice but to keep spending money until someone who cares about you intervenes.

    > Better caching
    > A huge chunk of CSS can be shared across products and properties.

    If “A huge chunk of CSS can be shared across products and properties” isn’t already a benefit of your CSS then, frankly, you’re doing CSS wrong. As has been pointed out, repeatedly, the only reason you get reuse with your technique is that you have a 1-to-1 mapping between a CSS rule and a specific value for a specific property.

    > Very little maintenance (on the CSS side)
    > Only a small set of rules are meant to change over time.

    But now all the maintenance is on the HTML side, many times over. Well done!
    (Note: sarcasm)

    > Less abstraction
    > There is no need to look for rules in a style sheet to figure out the styling of a template. It’s all in the markup.

    Worrying about styling when editing a template sounds like you’ve been working without a proper styleguide. I’m sorry about that, but that doesn’t excuse embedding styling information *in* the template.

    Imagine if someone comes by your desk tomorrow and says all the buttons that have descructive actions (delete, cancel account, etc.) have to be coloured red. Are you truly suggesting that it’s a positive step forward to have to search your entire template files to find all buttons, work out if they have destructive actions or not, and then change the markup to replace `class=”bgc-blue”` with `class=”bgc-red”`?

    Personally, I’d prefer to check my styleguide, delve into buttons.css and change:

    .destructive {
    background-color: blue;
    }

    …to:

    .destructive {
    background-color: red;
    }

    What document specifics are important, and therefore what should be semantically tagged, should be driven by your styleguide. The benefit of that is that while visual appearances may change, the semantic meaning of the document probably won’t. If tomorrow someone decides that all headlines should be purple, that’s a one line change and you get to go on building cool new features rather than playing template whack-a-mole.

    > Third-party development
    > A third party can hand us a template without having to attach a style sheet (or a style block) to it. No custom rules from third parties means no risk of breakage due to rules that have not been properly namespaced.

    This is another consequence of not having a proper style guide.

    Part of me is glad I don’t work on My Yahoo! anymore, as I wouldn’t want to deal with this level of fail. The other part of me wishes I was still there so that I could have fought against this nonsense. I’m just glad that, despite that the editor’s note implies, this hasn’t spread beyond my.yahoo.com, and I pray that it never will.

    To others who might be reading this: If you’ve made it this far and my arguments haven’t convinced you not to use this technique, I implore you to read the articles by Tim Huegdon (another ex-Yahoo) and Ben Darlow that others have linked to that offer additional, more in-depth coverage of why you’re much better off hooking into semantic class names for your styling.

    * http://nefariousdesigns.co.uk/on-html-element-identifiers.html
    * http://www.kapowaz.net/articles/cargo-cult-css

    1
    • 152

      Hi Steve,

      I believe you spent much more time writing your comment than reading this article, let alone my comments. I say this because many of the points you make have nothing to do with the technique I discuss here. And for this reason, I will not bother repeating myself.

      For your information, Jeremy Keith wrote a piece (http://adactio.com/journal/6537/) “comparing” the article you linked to with this one. It shows that things are not as simple as you are presenting them.

      “As a former Senior Front-End Engineer on the My Yahoo! team and former Front-End Architect at Yahoo!”

      Then you should be interested to know that we have boosted performance *big time*! We also have reduced file size by more than half. And 98% of our styles can be shared across the *network* – something you’re totally missing in your comment.

      Anyway, as it says at the bottom of the article:

      “tools, not rules”.

      Thanks for your feedback!

      0
      • 153

        The quotes – the points I responded to – were taken directly from the article. I wasn’t attempting to change your mind. You clearly have strength in your conviction, for which I applaud you. I was trying to present some pretty serious downsides and debunk many of your presented upsides for anyone else reading this article.

        As for “And 98% of our styles can be shared across the *network* – something you’re totally missing in your comment.” No no, I didn’t miss it. See: “As has been pointed out, repeatedly, the only reason you get reuse with your technique is that you have a 1-to-1 mapping between a CSS rule and a specific value for a specific property.”. Of course M-10 is reusable; it’s as reusable as style=”margin: 10px” would be. You seem to be valuing reuse over everything else. I’m saying that there are more important things than atomic reuse.

        1
        • 154

          Warning, this is a long comment but I thought I should address Steve’s comments as I believe they contain some “inaccuracies”.

          > As a former Senior Front-End Engineer on the My Yahoo! team
          > and former Front-End Architect at Yahoo!, I weep openly at
          > what has been done to a once fairly high-quality codebase.

          What does this have to do with anything? Did I play the “title card”? Should I say my “title” tops yours and call it a day? I think it’s better to articulate/lay out our arguments than claiming we have “special knowledge”.

          > Your ‘What’s Wrong With This Model?’ section sets up several strawman arguments.

          That’s an interesting claim. Could you elaborate and describe the fallacies or should we just take your word for it?

          > You then set off knocking down said strawmen, doing immense
          > damage to the future maintainability of your codebase

          I wonder how much do you know about our codebase? I know you worked on the product, but since then it has been re-done from scratch, on top of an entirely new stack.

          >> Simple changes to the style of our module have resulted in
          >> new rules in the style sheet. There must be a way to style
          >> things without always having to write more CSS rules.

          > Let me turn the second sentence around to show that your
          > solution is no better: “there must be a better way to style
          > things without always having to write more HTML”.

          Writing HTML (adding values to @class in this case) does not lead to bloat, nor poor caching; writing new rules in a styles sheet does both.

          > Again, turning the second sentence around: “Using a class
          > associated with these styles, rather than semantic class
          > names with grouped selectors, will lead to more HTML”.

          Actually, this is not true either, see:
          http://coding.smashingmagazine.com/2013/10/21/challenging-css-best-practices-atomic-approach/#comment-973837

          “Semantic” class names (names related to content) need to be long enough to be meaningful, which in turns creates more bytes than multiple atomic classes names.

          > Nothing you’ve written proves that these rules are harder
          > to maintain than HTML littered with presentational classes.
          > This smells very much like a strawman to me.

          This is what the article says: “Of our six rules, four are context-based. Rules that are context-specific are hard to maintain. Styles related to such rules are not very reusable.”

          How does that smell like a straw-man? Where is the fallacy?

          > Styles related to such rules are /less/ reusable than
          > one-property-per-rule presentational rules, yes. To say
          > they’re “not very reusable” very much depends on context.
          > It’s perfectly possible to write a reusable set of CSS rules
          > hooked into semantic class names.

          Styles tied to “semantic” class names (names related to content) cannot be shared unless you’re dealing with related content. If “atomic” class names are more shareable/reusable it is because they are content agnostic. We can use the exact same class names on totally unrelated templates. All these templates need to share is the way they are styled.

          > This sounds more like a lack
          > of familiarity with best practice web development than anything else.

          “Lack of familiarity with best practice”, really? Here goes another Condescension/Patronizing remark…

          >> RTL and LTR interfaces become complicated.

          > Again, only if you’ve not written your HTML and CSS with RTL and LTR in mind.

          That’s the point. With the atomic approach, one does *not* need to “[write] HTML and CSS with RTL and LTR in mind”.
          Can’t you see the difference here? For example, one uses the classes “Fl-start” and “Mend-10″ to get a float with a margin that will appear as expected regardless of context (LTR or RTL). There is no such thing as writing HTML *and* CSS.

          >> Less bloat. We can build entire modules without adding a single
          >> line to the style sheets.

          > “Less bloat”, by which I take it you mean “I didn’t have to write any
          > additional styles”, is demonstrably false. The additional styling
          > information is still there, it’s just in your HTML and not in your CSS.
          > In fact, if this module looks exactly like another module on the page –
          > or on any other page – you’ve now got more bloat rather than less because
          > you’ve duplicated the styles along with the markup.

          The styling is duplicated (in the markup) the same way as it would be with “semantic” classes. A “.testimonial” class would always map to the same atomic classes. If you have multiple “.testimonial” instances in your markup then you’d have the same mapping of atomic “classes” duplicated too. So I don’t see your point; also because as I mentioned above, more atomic classes does *not* mean more bytes.

          >> Faster development
          >> Styles are driven by classes that are not related to content, so we
          >> can copy and paste existing modules to get started.

          >> Copy and paste development really isn’t something to encourage. Copy
          >> and paste is the entry level of code reusability – everyone starts
          >> there, but you quickly learn that you’re just adding additional heads
          >> to the monster you’ll have to slay come refactor time.

          Actually, I was on the team that refactored yahoo.com and also on the one that refactored my.yahoo. Both times, styles sheets were thrown away. With the atomic approach it would not have been the case. Actually, I think we could have been able to save/re-use components if we had adopted a more granular approach.

          > You’ll be in a much better place if you just describe your content,
          > not what it should look like today.

          If you use templates, then giving a meaningful name to the file should be enough. In my opinion, *limiting* yourself to style things through semantic class names – in the name of best practices – is counter-productive. As this articles suggests, we should favor both approaches to achieve our goals. A “semantic” class name makes sense as a *needed* hook, not as a general rule.

          >> RTL interface for free
          >> Using start and end keywords makes a lot of sense. It saves us from having
          >> to write extra rules for RTL context.

          > “free”, where free is something that means a heck of a lot more work
          > embedding ‘put margin at start’ and ‘put margin at end’ class names in
          > your HTML. I liken this selling point to Candy Crush; it’s free until
          > you realise that you’ve spent hundreds or thousands of dollars/pounds/euros/etc
          > in in-app purchases. By the time that realisation bites, you’re so far down
          > the road that you have basically no other choice but to keep spending money
          > until someone who cares about you intervenes.

          This sounds like Reductio Ad Absurdum – which is an interesting argument coming from someone who keeps waiving the straw-man flag.

          >> Better caching
          >> A huge chunk of CSS can be shared across products and properties.

          > If “A huge chunk of CSS can be shared across products and properties”
          > isn’t already a benefit of your CSS then, frankly, you’re doing CSS wrong.

          Really? If “semantic” class names are meant to be related to content, how are you sharing rules between properties/products as different as yahoo.com, my.yahoo.com, screen.yahoo.com, finance.yahoo.com, sports.yahoo.com, omg.yahoo.com, etc.

          Would you be serving “.portfolio” rules across the board? Or “.leaderboard” ones. What about “.video-stage” or “.player-card”?

          > As has been pointed out, repeatedly, the only reason you get reuse with your
          > technique is that you have a 1-to-1 mapping between a CSS rule and a specific
          > value for a specific property.

          I think you are *totally* missing the point here. With the *same* 20KB (Gzipped) file we can build almost any Yahoo site.
          If we are short for something (if we do not have the styles for it), then a couple of KB takes care of extra customization (and that file is *not* bundled with atomic.css).

          >> Very little maintenance (on the CSS side)
          >> Only a small set of rules are meant to change over time.

          > But now all the maintenance is on the HTML side, many times over.
          > Well done! (Note: sarcasm)

          Transferring the maintenance from one layer to another does not necessary mean it is much more time consuming. That depends on your setup/workflow. Also, as noted in the article, “CSS changes may be quick to make”, but they are often nothing more than *shortcuts* (adding an *extra* *sandboxed* rule to the styles sheet rather than properly addressing the writing/optimization of that styling). Those changes are also more expensive (global scope) than a change of class name in the markup.
          Also, pushing a new CSS rollup is more expensive than updating a bunch of templates.

          >> Less abstraction
          >> There is no need to look for rules in a style sheet to figure
          >> out the styling of a template. It’s all in the markup.

          > Worrying about styling when editing a template sounds like you’ve
          > been working without a proper styleguide. I’m sorry about that,
          > but that doesn’t excuse embedding styling information *in* the template.

          Does it hurt accessibility? Does it hurt performance? Does it hurt the semantic of the document (for SE and AT)? What are you fighting against here? Is this all about *maintenance* then I’d suggest we trust people to weigh the benefits and costs of this approach.

          > Imagine if someone comes by your desk tomorrow and says all
          > the buttons that have descructive actions (delete, cancel
          > account, etc.) have to be coloured red. Are you truly suggesting
          > that it’s a positive step forward to have to search your entire
          > template files to find all buttons, work out if they have
          > destructive actions or not, and then change the markup to
          > replace `class=”bgc-blue”` with `class=”bgc-red”`?

          I find interesting that the strongest negative comments about this article show that their author did not read the article that well. In your case, I see that you missed the section “No More .button Class?” where I say we do have/use “semantic” class names. For example, for buttons, we have all these extra classes: .Primary, .Secondary, .Info, Important, .Success, .Warning, .UserPrimary, UserSecondary, .Btn-y, .Btn-fb, etc.

          >> Third-party development
          >> A third party can hand us a template without having to attach
          >> a style sheet (or a style block) to it. No custom rules from
          >> third parties means no risk of breakage due to rules that have
          >> not been properly namespaced.

          > This is another consequence of not having a proper style guide.

          A style guide would not allow *customization* of their templates. Third parties want freedom, we give them that without having to vest and embark external styles sheets.

          > Part of me is glad I don’t work on My Yahoo! anymore, as I
          > wouldn’t want to deal with this level of fail. The other part
          > of me wishes I was still there so that I could have fought
          > against this nonsense. I’m just glad that, despite that the
          > editor’s note implies, this hasn’t spread beyond my.yahoo.com,
          > and I pray that it never will.

          As Ben Frain rightly commented (http://coding.smashingmagazine.com/2013/10/21/challenging-css-best-practices-atomic-approach/#comment-973978), this is more related to adoption than anything else. The data is there. I know you’ve been carefully ignoring that part in your comments, but we’ve hard data and there is not much to argue about that.

          > I wasn’t attempting to change your mind. You clearly have strength
          > in your conviction, for which I applaud you.

          It’s not about conviction but *data*. Best proof is that I was convinced at first that this approach would bloat the markup, when in fact it does not.

          0
          • 155

            Correct me, if I’m wrong, but if your biggest concern is loading performance of long semantic class names (and imho – forgive me – the only point which could be taken as an argument for using atomic css), why not develop a css-minifier, which renames them, like javascript-minifiers do for variables? Wouldn’t that be the most efficient approach performance-wise?

            Another point is, that the user usually just needs to load a stylesheet once and that might be also true for returning visitors, while all the css classes you have in your html need to be loaded for every new element.

            And what I really really would like to hear, is an answer to the question, what makes this approach better than inline-styles… I even would suspect that there is not much difference in file-size, when gzipped.

            0
    • 156

      I really enjoyed this article and Ben’s article. However, I don’t agree with either of them. I will post my thoughts very soon. Ohhh yeah and up until 6 months ago I worked for The New York Times.

      0
  63. 157

    A bold and interesting article, Thierry.

    Just a couple of thoughts:

    1.

    Given the sheer number of declarations that would be accrued in your style sheet(s) using this atomic approach, I wonder whether you’d considered saving yourself a hefty http request (gzipped or no) by taking advantage of HTML’s style attribute.

    By localizing independent styles to individual elements, surely you would enjoy an even greater level of atomization?

    A class of .M-L-10 (for margin-left: 10) could be completely eliminated and replaced with the direct declaration of style="margin-left: 10px". Then, when you later change the value from 10 to 11.5px, you would only have to edit the document. The style sheet would be infinitely decoupled as it would not exist at all.

    2.

    Whether you use the class .sidebar or a combination of classes class="Fl-start Mend-10 W-25" is a moot point. The correct, semantic, accessible and documented (http://www.w3.org/TR/wai-aria/roles#complementary) markup is this:

    <aside role="complementary">

    You can style that directly ([role="complementary"] or body > aside or something) or you can squirt a bunch of classes at it, should you wish. Whatever floats your boat :-)

    0
    • 158

      Hey Heydon,

      My answers:

      1.

      Like the Venn diagram shows, we want to keep only the good parts of inline styling (scope and portability). A class of .M-L-10 only clocks at 0.0.1.0. versus 1.0.0.0 for @style.

      Also, we are not that verbose as there are many classes that we map with more than 1 declaration (float is an example, but we do the same for our grid units and others).

      Being less verbose means less bytes. At first, we thought that adding all these classes would start adding weight to our pages, but it turns out this is not the case. That’s because we usually have one meaningful/semantic class on a node associated with a bunch of *very short* ones. If you compare that to the classic way of doing things, where we have multiple meaningful class names OR with @style with many single property/value pairs then you see that the atomic weight is LESS bytes and *easier to read*.

      I mentioned in a previous comment, the classes applied to the list items on this section (comments), they are:

      comment even thread-odd thread-alt depth-1 clearfix

      The atomic way it could be something like this:

      comment My-10 Row Bd-1

      I won’t even mention @style here, as we both know if would be much more bytes, *and* markup is not cached. To me, @style has too much baggage”.

      2.

      I think we had this discussion elsewhere already. I said I *totally* agree with this approach, but I also said it is not realistic for authors who need to deal with oldIE. I’m not a fan of the shim and we can’t rely on the attribute selector. In other words, we cannot “leverage” <aside role=”complementary”>
      The best we can do is to use: <div class=”aside” role=”complementary”>

      Thanks for stopping by!

      0
      • 159

        Cheeky! You swapped my lovely <aside> for another <div> ;-)

        If you are concerned about oldIE, switching from aside role="complementary" to div role="complementray" doesn’t make any practical difference, since IE6-7 do not support ARIA anyway (http://caniuse.com/wai-aria). Using the shiv just means that the <aside> element’s semantics can be used in good browsers without breaking oldIE’s layout. That’s progressive enhancement.

        I – like yourself – don’t much like throwing javascript around everywhere to plug holes, but I see the shiv/shim as something of an exception: It’s a small script (a fraction of the size of jQuery) and is available from Google’s CDN (http://html5shiv.googlecode.com/svn/trunk/html5.js). It is used by more or less everyone who doesn’t use Boilerplate or Modernizr, so it’s probably cached too. I’m not going to give up the semantics of HTML5 entirely for the sake of saving a 4k (if uncached) request, loaded only conditionally for some browsers. No sireee.

        Regarding attribute selectors: The only browser which does not support [role="complementary"] is IE6. IE6!.

        For those reading who are interested in using more complex attribute selectors, selectivizr (http://selectivizr.com/) is a small, conditionally loaded, script that gives support for IE6+. This is pretty cool when you think of all the features that IE6 simply will not support ever, like SVG and local storage and sanity.

        A rare win when battling with defunct browsers, imho, and at not much cost?

        Thanks for the interesting debate and for the introduction to some intriguing metrics.

        0
  64. 160

    Of course since you’re working on your own you can even use inline styling, nobody is going to stop you, you feel comfortable that way. But the main reason for splitting behavioral, presentational and structural code is NOT to make it easier to code, it’s for some other reasons:
    1. making it easier to maintain, usually BY A TEAM, because people in a team have different kinds of skills, and are responsible just for their own field.
    2. making overall size of a project (bunch of HTML, JS and CSS files) smaller.
    this approach makes CSS files smaller, but bloats HTML with junk.
    3. mixing these 3 layers (and they’re not just 3, there’s more sometime) forces you to edit both HTML and CSS files when you’re applying a minor “style” change.
    4. consider changing the style for a specific panel on the whole project, do we really like to replace every occurrence of that code in our files (I know it’s simply possible by batch-replace)? If you remember that early times of CSS, it was the best part of CSS coming around; change it in one place, get it done everywhere.

    enough for now, although there’s too many other issues that comes in my mind.
    no matter you name your classes Mi-6 or end-4343-top-mi19-shaded, it may be more professional-looking James-bond style code, but technically you’re writing worse than inline stylesheet.

    0
  65. 161

    There is nothing wrong with being an evangelist for standards when the standards were derived for very good reason. I’m no purist for purist sake. The ideas stated in this article strike me as antithetical to everything I try to teach people, and an atrocious way of going about things. No wonder Yahoo’s site makes me itchy.

    Everyone else has already stated all the reasons.

    Bottom line is – you can avoid CSS bloat if you know what you’re doing with CSS. Then you have the best of both worlds.

    0
  66. 162

    Lol why don’t just write inline css then

    0
  67. 163

    Very interesting. Very useful.
    I suspect that this is best used in HTML templates. And perhaps only there. Here’s why.
    It occurs to me that the original reason why CSS was invented was because it was impractical to manually edit hundreds of hand-written HTML files in order to change a website’s appearance. Back then, real-time HTML templating was pretty much non-existent. But HTML templates are able to solve that same problem.
    If you think about it, HTML templates and CSS files serve a similar overall purpose in that they are re-usable text files that control presentation. Both function independently of the content. Therefore both are easily edited and re-usable.
    Technically, they’re written in drastically different languages and applied in drastically different ways, but their overall purpose is actually very similar.
    Because of that, there’s nothing wrong with attaching CSS styles to HTML templates, even inline, because they are still separate from the content. Even if you had to update every single template, there still wouldn’t be very many of them because they’re re-usable… just like CSS files. Both are external text files. You can have as many or as few as you like.

    0
  68. 164

    Nice. I see how this could be great for huge sites where markup was open to editing. One potential problem I see is with responsive layouts. What if I want an element with a 4 pixel border on the desktop, and a 2 pixel border on mobile? What class name do I give the element? “.border4and2?”
    and that’s just a very simple case. For an a non-adaptive approach, with any complex art direction, where you’re serving the same content across devices, with multiple, complex breakpoints, this could get confusing pretty fast.

    0
    • 165

      While I don’t agree with how far this approach takes atomic reuse and style-in-content, I can answer answer your question :

      You’ve probable seen something like this before if you’ve used a grid system before : “.twelve” = 100% and at <768px screen resolution you'd switch to a two (out of four at mobile) column structure. That's the general idea, anyways.

      0
  69. 166

    I think this is a really bad approach and no way different from inline styling. The purpose of CSS is to separate styling from markup. Think about it; if a single CSS class represents a single CSS style declaration, then there IS NO separation between markup and styling, because the styling IS IN the markup as an ALIAS. Ideologically this is very wrong. Changing the class names to something else than the semantic equivalents will not help, because the you have effectively only developed an inline styling language of your own.

    0
    • 167

      I generally agree with you, except on one point.

      The purpose of CSS WAS to separate styling from markup… because HTML templates didn’t exist at the time that CSS was invented.
      It soon grew into a greater ideal: To separate styling from CONTENT.

      Therefore, it might be okay to do something like this with programmatically generated HTML, such as HTML templates, which are inherently separated from content.

      0
      • 168

        It seems to me like you are implying that if a web page is generated by, say, a CMS, the content is no longer in the HTML, but in a database, am I correct? That is not true. The content, be it in a database or an XML file or whatever, in order to be presented in a browser, is always presented in HTML, in one way or another. HTML templates are just a means to make easier the marking up of recurring content, ie. automation.

        If you produce an HTML page with an empty H1 it doesn’t mean there is no content. It means the content is nothing. I would like to say that markup is practically the same thing as content, but that is not ENTIRELY true. Rather, in the context of www, they can not exist without each other. Where there is markup, there is ALWAYS content (the content can be nothing, remember) and where there is content, it needs to marked up, otherwise it’s badly composed content.

        0
  70. 169

    Martins Barinskis

    October 25, 2013 12:15 am

    Hi Thierry,

    Thanks for the very interesting and controversial article.
    Just a few notes from myself.
    * I come from an organization that uses a very similar approach to the one you’ve described here. Although I consider myself quite a purist when it comes to CSS class naming and SoC, I cannot deny there are really significant gains in code maintainability and component reuse with the atomic approach.
    * Atomic classes work really well if they define only box model properties – “margin”, “padding” and “border”, probably “display” property could work well too. Be very careful with those properties that are inherited, “text-align” for example, as in the future you might be tempted to use some really ugly template selectors to override this for the child elements.
    * Might be obvious but still: don’t use atomic classes in conjunction with another classes to override their property values:
    .comment.M-T-10px {
    margin-top: 20px; /*very, very bad*/
    }

    Thanks again,
    Martin

    0
  71. 171

    This article is a masterful exploration of Poe’s law. Kudos all round.

    0
  72. 172

    Michael (Minneapolis Designer)

    October 25, 2013 4:20 pm

    Interesting idea. Not sure I agree but I think I’ll give it a try on my next project on a limited basis. I can see it being a good approach with portions of a page. Like most conflicting ideas a hybrid of multiple approaches on a project tends to lead to the best results.

    0
  73. 173

    Makes complete sense for large companies with many sites and apps to maintain. I usually check out what WordPress is doing or look at their theme code/source code to get an idea of what developers are doing, WP devs are really good at what they do and same with Google. Those two set a great standard of coding to follow. This is still a good idea for the right application.

    0
  74. 174

    This is great, is like work with bootstrap, but the HTML incomes to be more large.

    now it will be

    We have a good option because it will be more understand “able”, and maybe we simply copy and paste and generate our framework. but when we start to generate HTML elements (like dynamic content) we spend more time adding and removing classes.

    What do you think?

    0
  75. 175

    You might like the grid framework I made based on this technique.

    https://gist.github.com/wycks/5566134

    0
  76. 177

    Manuel Kammermann

    October 29, 2013 1:37 am

    As a developer I can see this technique solve a lot of acute styling problems like “this single box needs to be floated to the right”. However I think it will not be able to cover the following everyday use cass.

    1. Developing a website for someone/some company mostly should be easy to enter content and while automatically should look like the all the other similar contenct on the webpage. As most editors are not involved with typography you cannot leave it up to them to style the content. You would need an easy way of applying all those classes to the content-container.

    2. Wegpage redesign: all content should newly have a 15px margin-bottom from theihr headlines. How do you change this in an easy way (most probably you have the mb-15 class applied to many tags?

    I am not convinced this technique is maintainable for customers that focus on content.

    0
  77. 178

    Christopher Sanders

    October 29, 2013 6:20 am

    So you got some small benefit from making unmaintainable rotten code and now that warrants an article on the virtues of mixing presentation with markup. The only thing that is constant is change. This creates classes that are inflexible and are no better than writing inline styles simply to make the stylesheet smaller. It is beyond hideous to look at. New developers have to learn yet another language other than css to simply style the document. Every time there is a styling change you have to go in and change the html on the backend instead of just changing the stylesheet. I’m sorry but the workflow is terrible along with the ugly code that doesn’t describe the content it is presenting. Now you have elements not related to each other totally dependent on the same classnames. Sure it saves some bytes in the short-run it makes new features and other changes nearly impossible in the long run. I’m curious…how much did adding 5 classes per html increase the file sizes of the html documents.

    The claims…
    Less bloat
    We can build entire modules without adding a single line to the style sheets.
    (this is suspect becuase we don’t know how much it increases the size of html pages.)

    Faster development
    Styles are driven by classes that are not related to content, so we can copy and paste existing modules to get started.
    (Again suspect because we aren’t doing inline styles here so new team members have to learn another language on top of css.)

    Better caching
    A huge chunk of CSS can be shared across products and properties.
    (This is probably the only one of these “benefits” to actually pan out. Better caching of CSS but not so much for the HTML.)

    Very little maintenance
    Only a small set of rules are meant to change over time.
    (Potentially on the CSS side of things if you have a very small system. However, you trade the change in the css to a change in the HTML. Shifting the maintenance isn’t the same as very little maintenance.)

    Less abstraction
    There is no need to look for rules in a style sheet to figure out the styling of a template. It’s all in the markup.
    (Why not just write inline styles? I guess no one has ever heard of firebug or inspector.)

    Third-party development
    A third party can hand us a template without having to attach a style sheet (or a style block) to it. No custom rules from third parties means no risk of breakage due to rules that have not been properly namespaced.
    (This doesn’t actually mitigate that risk. It creates more single points of failure.)

    0
    • 179

      Christopher Sanders

      October 29, 2013 7:08 am

      Whoops! I wasn’t done editing my post. I hope I didn’t sound too harsh in that. I re-read it and it sounds harsher in tone than I wanted to. I wasn’t quite finished editing. Plus I wanted to edit for grammar and for accuracy….but the point is still the same. I do not agree with this. However, I appreciate the article, the discussions and remembering why the best practices became best practices in the first place.

      0
  78. 180

    I think a lot of people missed the point of this technique. It’s not for just any site, but if you have a modular, CMS-driven ecommerce site or something of that nature where the layouts are consistent and adhere to a grid something like this makes sense. If there are a lot of elements with a 20px left margin, or a consistent copy formatting, something like this can be beneficial. At the same time you have to be careful to implement it thoughtfully or it’s possible to paint yourself into a corner. But if it’s all planned out from the beginning it could work well for those specific implementations.

    1
  79. 181

    For me this looks like creating a .h files in C++ that #define all the stdlib functions to something different and then say that it’s much better now. Maybe it is, for you. However I think other people are pretty confused.

    To clarify, why to define css classes at all then?

    This is already 100% supported:

    style=”margin-bottom: 25px”

    What you propose here is just different syntax:

    class=”margin-bottom-25px”

    Why? Is the CSS syntax flawed?

    0
    • 182

      Hi Peter,

      > To clarify, why to define css classes at all then?

      You may want to check the Venn diagram and **read** the section titled “REGARDING MIMICKING INLINE STYLES”.

      0
  80. 183

    I don’t really understand how this would work on situations where the style needs to be swappable.
    Isn’t that the whole point of writing minimalistic and semantic HTML and then applying styling on top.

    For example a real world example:
    A huge news site (like news.yahoo.com) with hundreds of styled pages and templates for content creators to use.
    The HTML provides just the bare minimum, it just contains the actual content.
    Everything else is done with CSS.

    So redoing these hundreds of templates for each domain in use?

    Now comes the difficult part, the site has multiple domains with totally custom design on each. Not only simple things like graphics, but the whole layout and arrangement is different.
    But both share the same HTML, just the CSS files differ.

    0
  81. 184

    I know some real world examples I have worked on that would have been benefitted of using this approach. All of them have one common trait: they use a unique set of CSS files that define the complete style of its pages, and those files only change to add or update rules that, usually, involve editing the HTML code with new specific classes.

    Sadly, I really think that most websites (especially big ones) follow this pattern.

    If you know in earlier stages of the web development that your site is following this pattern, maybe you should really consider using this approach.
    If you dont’a have the time or resources to do it yourself, you even could consider using a front-end framework (like twitter bootstrap) that implement this kind of design (and customize it to your liking).

    However, I’m of the opinion that, for really good websites who allow style swapping, is better to write semantic HTML and then apply styling on it.

    0
  82. 185

    The CSS used by this technique seems so soulless, like a stranger interpreting a design manual written by someone they’ve never met.

    0
  83. 186

    I think using a combination of the methods would be the best. I agree with changing the layout and styles within the HTML, but I also think it can work to keep things a little more generic such as .border-thick and .border-thin that way you can change the padding for the one class and it will change everywhere, yet your not re-writting the CSS.

    0
  84. 187

    Interesting read! This is exactly what Twitter’s BootStrap is doing! Always looking for new ideas for implementation.

    0
  85. 188

    Am I the only one that noticed that the LTR/RTL comparison is apples to oranges?

    The initial example states that RTL changes need to “undo” LTR styles (indicating one style sheet for everyone), but then the “solution” talks about sending different assets (“Adaptive” design). The solution gets RTL for “free,” because RTL gets a different stylesheet altogether.

    Why wouldn’t you just send RTL/LTR specific stylesheets? Or, just wrap your styles in .ltr/.rtl in a similar manner to media queries or other client-specific code (this becomes extraordinarily easy with a preprocessor that allows nesting). Either would solve the LTR/RTL issue with the initial example.

    Also, how is M-10 different from border4px? As soon as you change the content in the M-10 style declaration, it becomes misleading, just like border4px does. “Just create a new rule,” you’ll say. I thought that was what you were trying to avoid. Plus, you have to then touch every single file that uses M-10 where it should now use, say M-15, and change the class. Blatantly violating the very W3C principle you mentioned, for the very reason (maintenance) you said it was intended for.

    0
  86. 189

    Fantastic article.

    It is truly fascinating to see someone actually implementing these revolutionary ideas. Even if the notion of atomic css doesn’t become common between developers, it’ll anyway push front-end developing in the right direction.

    Thanks!

    0
  87. 190

    Hi, I have also written a similer post on Object Oriented CSS, might be useful read http://ajwebdesigner.in/blog/css-best-practices/

    0
  88. 191

    Excellent article, Thierry. It seems like there’s a lot of continued discussion and detailed analysis of your article. The best takeaways for me are the following:

    If you’re writing CSS for a site that only YOU manage, write it however you want. Who cares?

    If you’re writing CSS and you’re on a team – whether it be small or large – just keep it concise, recognizable, and reusable.

    I’ve sent this article to dozens of my designer friends because it’s awesome.

    0
  89. 193

    HTML for Semantics, CSS for Styles and JavaScript for Behaviours.

    If I want to change my styles or even completely redesign my website then I’ll simply adjust / rebuild my CSS file. The HTML and JavaScript should be fine, because they do their own thing.

    But with your approach I’ll have to filter through and nit-pick every element in my HTML, on every page, on every site trying to remove or change an ocean of duplicated classes.

    Why should I have to edit X amount of HTML pages when I could simply edit one CSS file?

    0
  90. 194

    A good article to get you to think differently.

    I think it’s great to use this type of approach in some cases – common formatting options like m10 for margin:10px or brand-color for a brand specific text color can be helpful in consolidating some CSS into re-usable “atomic” classes.

    My issue comes with mass implementation. As many on here have already mentioned, this becomes a nightmare to manage on bigger sites.

    0
    • 195

      After re-reading the article and thinking about this topic, it seems to me that this logic does not make much sense at all.

      This type of styling actually does the opposite of what the author is trying to avoid. Let’s take a simple example:

      ul
      li class=”m10 p5 row”
      li class=”m10 p5 row”
      li class=”m10 p5 row”
      /ul

      In the above example, you had to “style” each list element individually using class names. Even though they use shared classes, each element needed to be modified, or it would not achieve it’s wanted style.

      That is the equivalent of doing the following in CSS:

      ul li:nth-child(1){
      margin: 10px;
      padding: 5px;
      display: block
      }
      ul li:nth-child(2){
      margin: 10px;
      padding: 5px;
      display: block
      }
      ul li:nth-child(3){
      margin: 10px;
      padding: 5px;
      display: block
      }

      Writing CSS like this would be a disaster, no different than doing the same in the markup. Now imagine if that list item was located in 3 parts of a page, on 15 pages – you would have to manually edit 45 elements. You would have to QA 45 elements. And you would have to maintain 45 elements. All in the name of saving yourself from the below:

      div#verySpecific ul > li {
      margin: 10px;
      padding: 5px;
      display: block
      }

      0
      • 196

        Please **read** the article (or some of the comments). The parts where it mentions “changing context” – styling via templates rather than via style sheets.

        0
    • 197

      > As many on here have already mentioned, this becomes a nightmare
      > to manage on bigger sites.

      I guess you missed the part in this article where I say we use this on my.yahoo.com.

      0
  91. 198

    Firstly please accept my apologies for not being able to read all the comments, I was curious to see what others thought but their were too many comments to appreciate them all.

    I’m glad you shared your knowledge with us. I’m very passionate about how CSS and the way we author it and I think its very important to keep an open ear to challenging current best practices.

    I mostly work with applications or highly functional websites so I’m very keen to keep consistency in and out. I believe that there will come a point where front-end engineers/designers/developers will begin to adopt a new workflow which consists of abstracting the computed HTML and CSS from their architectural building of an app or site. In fact it’s partially already happening. Take preprocessors for example or domain specific languages like SASS or coffeescript. For me HTML and CSS are just a means to an end. The real building will happen in a language (or languages) where I can describe behaviour, structure and style (which all overlap) without having to worry about reliance on limited language constructs. Just as an example take the discussions going on in this very thread about semantic class names. We’re looking for a way to label a property or group of properties without creating a direct link to its appearance in case it’s changes. Now you could create an abstract label which is void of any appearance, but then you risk making the architecture of the markup hard to understand (this is hard to explain to I’m simplifying slightly). If it were possible to describe the relationship of changes to properties rather than reaffirming them then our markup might be easier to manage and understand. Unfortunately CSS is partly to blame for this because it doesn’t allow us to modify properties between objects, as in it’s not possible to describe a property based on the value of a property in another selector. What I like to think would be true OOCSS. If we could write organic patterns like this we could avoid the maintenance issues that come with current practices. I think it’s coming but we’re still discovering what it is.

    0
  92. 199

    I do appreciate what you’re going for here, DRY, reusable, optimized CSS. That said I don’t see how this technique avoids the problems you attribute to other methods, specifically bloat.

    Your M-10 for a 10px margin for example. As others have pointed out, if you need a 20px margin, it means one of three things. Creating new rule which you say is wrong. Changing the existing rule without changing the class which we can all agree is bad. Or, change the rule and rename it in two places which is more work.

    “A NEW REQUIREMENT COMES IN. Suppose we now need to be able to display the image on the other side of the text as well.” If you need both options you need both rules regardless of technique.

    “Simple changes to the style of our module have resulted in new rules in the style sheet.” Not always. In many cases it means changing an existing rule, at least if you’re using class names that don’t reflect style.

    “There must be a way to style things without always having to write more CSS rules.” There’s not. If you change style you either need to write a new rule or change an existing one. The alternative is to create what you call a pool of styles. How can you possibly account for every Atomic rule in advance? I can see this having the potential to get just as bloated as any other method.

    It seems that this method is well suited for the situation you work in, a large, possible dispersed team, managing several web products that require a consistent style. I can see how this technique can benefit people in that scenario. That’s not the world most work in. Those of us that work on projects that share little or no common style will find little advantage from this technique.

    “In other words, we’d prefer to pollute the markup rather than the style sheet.” Why? Correct me if I’m wrong, but CSS can be minified and compressed where HTML cannot. Aren’t you just moving the problem from place to another? What we should be working towards is not polluting anything.

    This technique requires new team members to learn a new language. M-10 could mean anything until someone explains it. Until then these names are as understandable as hieroglyphs, petroglyphs, or pictograms. That lack of immediate clarity is deal breaker number one.

    To my way of thinking this technique prioritizes the reuse of styles (css) over the reuse of content (markup), which really doesn’t sit well. Let’s say I create a chunk of markup for a comment component. If I use a bunch of presentational classes as this technique proposes there’s no guarantee the styles will work in the new page design. Again, we all don’t work on products that share a significant amount of common styles.

    I, for one, still believe semantics are important. I know you’ve said you can use this along with semantic names but littering the markup with these non-semantic classes only makes things harder to maintain in mind.

    “If you check the W3C’s “Tips for Webmasters,” where it says “Good names don’t change,” you’ll see that the argument is about maintenance, not semantics per se.” They are absolutely talking about semantics. The examples they give are clearly semantically meaningful names.

    Let’s not gloss over the fact that new semantic elements in HTML5 came about because those were the semantic class names used by so many developers. Microformats are based largely on the use of semantic class names and came about in much the same way as the HTML5 elements.

    Google, and I suspect Yahoo and other search engines, use these semantic microformat class names to create those rich snippets. Who knows what semantic class names will become a new microformat tomorrow?

    That’s all I got.

    0
  93. 200

    Check out http://jslegers.github.io/atomic-navigation/ for several navigation elements implementing an atomic CSS design pattern.

    You can also check out http://www.cascade-framework.com/ for an entire CSS framework based on Atomic CSS design patterns.

    0
  94. 201

    I also commented on the “atomic” article referred in this article.

    While I do think we are heading in the right direction (SMACSS), I also have the feeling we are now reaching a point where it depends on the type of project which method we use (and also workflow and/or personal preference).
    All methods have some merits, and downsides, and there doesn’t seem to be one “global” method, that works flawlessly between every type of project (from a small “flyer-website” to a full-blown responsive “social-media” platform.

    I think the next step we need to take, is make our platforms (I’m using Drupal myself) “smart”. The CMS should be aware of your (S)CSS files, and be able to read them, and alter them.
    This way we would be able to take away a lot of hurdles: Naming conventions could become more readable, the CMS would replace long classes, by short ones, both in the stylesheet, and the output of the CMS. You would be able to see which styles aren’t used anymore and provide a safer way of CSS cleanup. And the CMS would be able to strip all classes and ID’s from it’s output, which aren’t defined in your stylesheets.
    You could then have easily readable stylesheets, which get converted once you go in production mode (like the aggragation of CSS files). It would become more easy to identify obsolete styling, and it would remove all unused classes/ID’s from the output of the CMS. And maybe some other cool stuff I haven’t thought about yet (perhaps some ‘styleguide’ generated page, that outputs all elements you have defined in your stylesheets?)

    But maybe this is a lot harder to build then I imagine… :(

    My 2cents :) because i’m noticing all these new methods of styling have their merits, but there is no “one method to rule them all”. And i think our tools have to become smarter in order to help us evolve further in front-end styling.

    0
  95. 202

    I believe good CSS practice starts with solid site mockups in Photoshop/Fireworks/Illustrator. That means a client has to actually approve all the details of your design while in mockup mode. If the client is asking you to move your design elements by 15px, then something got broken during the communication chain.
    We are not going to agree about how to approach CSS coding unless we agree that good css/html structure starts with good mockups. A modular or object oriented approach to CSS has to start with a mockup that allows for that. As you start drafting your mockup, or even your first wireframe, you have to take this into account.

    We should all learn to build websites how builders build houses. You start with a plan. During the planning phase you should calculate how much materials you need to build a house, and how much materials will cost you. In web design’s case you need to already know what materials you would require to build the site before drafting it, and how much css/html/js it might need to be accomplished.

    Once the blue print is ready, the builder starts with the foundation and framing. In second stage he applies sheetrock and insulation. In third stage he does all the detail work, such as trim, paint…etc. We as designers need to follow the same principle. You start with the site structure. Reset, rows, columns, blocks, containers…etc. Then you add a form to your structure, and lastly you do all the detail work. The problem is, most designer build their site from top to bottom. That is where most problems occur, because if you first get done with the header you cannot foresee if some of that header code can be used in the footer, so your code starts looking bloated as you go down the page.

    0
  96. 203

    Examples of this approach at the bottom of this comment.

    Preface: I do not agree with the use of meaningless class names. Instead of .m-10 assuming that it would add a 10px margin around the element, we use something more along the lines of .man, .mas, .mam, .mal. (margin-all-none, margin-all-small, margin-all-medium… so on.) This allows us to changes those easily on the project (since we have built a framework) and of course everything is relative to font-size (so in em’s) and everything scales nicely with it. If anything goes over margin-all-large (20px by default), then we will add it to a context specific rule.

    Balance: There is a balance you have to strike, you can’t go heavy one way or the other, you have to learn to make good decisions and determine when to write a new rule or when to not.

    For those non-believers, we use this approach on massive sites and it is the saving for keeping our CSS tight and solves code bloat. There are advantages and disadvantages to this approach:

    Advantages:
    1. Cacheing
    2. Not bound to context = more modular
    3. Basically everything said in this article

    Disadvantages:
    1. What about Responsive D00D? (easy, just pull it off the html and style it in the stylesheet)
    2. May require some touch-up after prototyping (if you do prototyping)

    For examples of our hybrid approach in action visit the following websites:
    http://www.heifer.org
    http://www.perotmuseum.org/
    http://www.klydewarrenpark.org/

    Our Open Source Responsive Framework that uses a hybrid approach.
    http://getmotif.com
    https://github.com/MotifFramework/Motif

    0
  97. 204

    This is a terrible article with naming conventions for atoms. However there is merit in this article and in this practice. I often come across sub modules that have the same code between objects. Mostly for radius and padding. Sometimes, it doesn’t make sense to scope them to an module. Also, I notice that my utility classes are growing because of all the exceptions in sub modules. For example, I might want to tighten up the vertical rhythm on a well for the homepage.

    Here is my thought on all of this: Avoid sub modules if you can do it with atoms.

    1. Use atoms to handle what sub modules do. (pa-s, pa-m, pa-l)

    2. Write them before your atoms so atoms can trump default values. (see the box object in my code)

    http://codepen.io/anon/pen/lwinG?editors=110

    2
  98. 205

    I think a lot of people are taking this too literally…I don’t think he’s saying to use this convention for ALL your CSS. A combination of both techniques is probably the best.

    For example, I’ll style all my header tags a certain way, that way, if I need to change them all, it’s one simple change to the CSS. But sometimes I need different margins on them in different areas – that’s when I use “mb10″ or “mb20″ – for “margin-bottom:20px”. Now if I need to change the margin on that one element, I’m changing it one place instead of creating a new class.

    The whole point of style sheets was to remove styles from the markup, and if you have multiple items with the same style, you only have to change that style in ONE place, not everywhere it’s located in the HTML – that seems like an obvious benefit.

    Using only his system seems counter-intuitive to me, for the reasons a lot of people have mentioned. However, it can be used effectively, in small doses, to help with maintenance. It’s best just to try it and see what works for you – all situations are different.

    0
  99. 206

    I wanted to elaborate a bit on a previous post and give Trev a virtual fist-bump for using both together like they should be.

    I am going to use four very common objects for my example, none of which are an abstraction of one another. Each serve a unique role.

    They are:

    .box – used to box off content from the rest of the page
    .alert – used for alert messages
    .label – used for creating inline labels on forms
    .btn – used for creating buttons that can be placed on input tags and link tags

    Now let’s say we have a design requirement to make smaller and larger sizes of each. Easy enough, I will either divide the padding in half, or double it.

    .box-s, .alert-s, .label-s, .btn-s { padding: 12px; }
    .box-l, .alert-l, .label-l, .btn-l { padding: 48px; }

    See the problem here? What if another design requirement comes up for a input box with the same sizing options. I’d have to add it to then end of the list. Modular design “best-practices” is creating a problem that it claimed to help fix, bloat. Of course the solution would be this:

    .pa-s { padding: 12px; }
    .pa-l { padding: 48px; }

    It is not scoped to an object. It’s generic – simple. Now of course since atoms can not target child elements, you will still need submodules here and there. For example inuit’s .grid has a flush submodule that can not be replaced with atoms:

    .grid-flush > .grid-item { }

    However, most submodules can be eliminated. Remember Nicole Sullivan’s media object? You know, that little component that we heard about 5000 times that saved Facebook a gazillion lines of code? Like the author pointed out, that is overscoped considering .media-left and .media-right’s ruleset can be used outside its modular’s container.

    The funny thing is, most experts hate what Yahoo is doing. Each time I e-mail them asking their feelings about unscoped submodules (or atoms), I get the same tired old response of “limit your helper functions,” or “keep things like ‘float’ inside submodules.” I’m not going to name names, but I can’t imagine writing a site without a hefty amount of them in it.

    I used padding as an example, but I have so many sites that have exceptions to the margins between elements, alignment of text, etc. So many time was saved writing sub-modules by atoms.

    In closing, remember two things:

    1. Never believe a person who says something is “best practice” blindly

    - ESPECIALLY if they write books or appear at Webstock ;)

    2. I said it before, ignore the naming convention of atoms here.

    - Use things like xs, s, m, l for sizes.

    Eric

    0
    • 207

      “So much time,” not “so many.” I’m very tired and pron to both grammatical and spelling errors.

      0

Leave a Comment

Yay! You've decided to leave a comment. That's fantastic! Please keep in mind that comments are moderated and rel="nofollow" is in use. So, please do not use a spammy keyword or a domain as your name, or else it will be deleted. Let's have a personal and meaningful conversation instead. Thanks for dropping by!

↑ Back to top