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 Link

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 Link

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 Link

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 Link

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 Link

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

Markup Link

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 Link

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 Link

The image is now displayed on the opposite side:


me
10

@thierrykoblentz 14 minutes ago

One More Requirement Comes In Link

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 Link

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 Link

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 Link

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


me
11

@thierrykoblentz 14 minutes ago

What’s Wrong With This Model? Link

  • 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 Link

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 Link

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 Link

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 Link


me
17

@thierrykoblentz 14 minutes ago

What Is This about? Link

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? Link

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 Link

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 Link

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 Link

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 Link

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 Link

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 Link

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? Link

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? Link

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? Link

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 Link

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 Link

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 Link

  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 top Tweet itShare on Facebook

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.

Advertisement
  1. 1

    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
    • 2

      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
    • 3

      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
    • 4

      “…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");

      -2
      • 5

        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
  2. 6

    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?

    2
    • 7

      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.

      1
    • 8

      Now, that’s a very good question!

      0
    • 9

      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
      • 10

        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
        • 11

          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
      • 12

        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
  3. 13

    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.

    -7
    • 14

      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
      • 15

        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
  4. 16

    great way to make simple things complicated.

    5
  5. 17

    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.

    5
    • 18

      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.

      4
      • 19

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

        2
        • 20

          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.

          -1
          • 21

            You’ve heard of Firebug, right?

            1
          • 22


            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.

            8
    • 23

      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.

      3
  6. 24

    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.

    5
  7. 25

    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.

    5
  8. 26

    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.

    -2
  9. 30

    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.

    1
    • 31

      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
      • 32

        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.

        1
        • 33

          …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
  10. 34

    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
  11. 35

    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
    • 36

      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
      • 37

        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.

        2
        • 38

          “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
          • 39

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

            2
  12. 40

    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.

    3
    • 41

      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.

      -1
      • 42

        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.

        2
      • 43

        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.

        1
      • 44

        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.

        1
        • 45

          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
        • 46

          “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
      • 47

        Everybody is getting stuck on the 10px thing. Personally I’d do something like padding, padding small, padding * 2… I think this is really good but, Is there not a way to define these atomic elements and then @extend them together to make (almost) everyone happy.

        Also, on the short names, why couldn’t you leave in the longer descriptive names and have your preprocessor shorten them on push to a test or prod environment?

        0
  13. 48

    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.

    1
    • 49

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

      -1
      • 50

        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
  14. 51

    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.

    1
  15. 52

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

    -1
  16. 53

    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.

    1
    • 54

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

      1
      • 55

        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
        • 56

          “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
      • 57

        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
      • 58

        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
    • 59

      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
      • 60

        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
  17. 61

    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
    • 62

      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
      • 63

        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
        • 64

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

          3
          • 65

            which defeats the whole purpose of a “style sheet”

            0
          • 66

            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
          • 67

            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.

            5
      • 68

        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
        • 69

          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
        • 70

          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
  18. 71

    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
    • 72

      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
  19. 73

    Are classes more preferred over ids?

    0
    • 74

      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
    • 75

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

      0
  20. 76

    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
    • 77

      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
      • 78

        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
  21. 79

    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
  22. 80

    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
    • 81

      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
    • 82

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

      0
  23. 83

    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
  24. 84

    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
    • 85

      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
    • 86

      This is a very good point.

      0
    • 87

      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
      • 88

        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
  25. 89

    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
  26. 90

    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
  27. 91

    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
    • 92

      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
      • 93

        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
        • 94

          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
  28. 95

    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
  29. 96

    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
  30. 97

    Benjamin Gandhi-Shepard

    October 21, 2013 6:55 am

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

    0
  31. 98

    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
    • 99

      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.

      1
  32. 100

    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
    • 101

      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
  33. 102

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

    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
    • 104

      “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
      • 105

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

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

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

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

    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
    • 112

      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
      • 113

        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
    • 114

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

      0
  39. 115

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

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

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

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

    0
  43. 121

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

    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
    • 123

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

      0
  45. 124

    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
    • 125

      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
      • 126

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

    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!

    1
  47. 129

    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
  48. 130

    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.

    -1
  49. 131

    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
    • 132

      This does not prevent us from doing RWD. Please read previous comments to see how we do it.

      0
  50. 133

    “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

↑ Back to top