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

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

Challenging CSS Best Practices

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 https://www.smashingmagazine.com/2012/04/20/decoupling-html-from-css/
  2. 2 http://nefariousdesigns.co.uk/on-html-element-identifiers.html
  3. 3 https://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 https://www.smashingmagazine.com/wp-content/uploads/2013/10/venn-diagram_mini.png
  22. 22 https://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
SmashingConf Barcelona 2016

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

↑ Back to top Tweet itShare on Facebook

Advertisement

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.

  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

      Gabriel Izaias

      October 21, 2013 4:32 am

      Now, that’s a very good question!

      0
    • 9

      Thierry Koblentz

      October 21, 2013 7:29 am

      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

          Fredrik Carlsson

          October 24, 2013 2:26 am

          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

      Thierry Koblentz

      October 21, 2013 8:31 am

      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.

        -1
  4. 16

    great way to make simple things complicated.

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

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

          Fredrik Carlsson

          October 24, 2013 2:55 am

          Here is how I see it:

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

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

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

    Colin Wiseman

    October 21, 2013 4:38 am

    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

      Thierry Koblentz

      October 21, 2013 9:16 am

      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

        Anthony McLin

        October 23, 2013 6:24 pm

        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

    Elton Mesquita

    October 21, 2013 4:52 am

    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…

    0
    • 36

      Thierry Koblentz

      October 21, 2013 11:36 am

      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

            Anthony McLin

            October 23, 2013 6:27 pm

            (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

    Andrew Hallock

    October 21, 2013 6:30 am

    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

      Thierry Koblentz

      October 21, 2013 10:37 am

      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

        Michael Havard

        October 21, 2013 11:43 am

        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

        Andrew Hallock

        October 21, 2013 12:17 pm

        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

          Mike Petrovich

          October 31, 2013 6:51 am

          “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

      Thierry Koblentz

      October 21, 2013 10:40 am

      “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

        Jonathan Stilts

        October 21, 2013 5:46 pm

        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

      Thierry Koblentz

      October 21, 2013 12:19 pm

      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

          Thierry Koblentz

          October 22, 2013 9:31 am

          “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

        Anthony McLin

        October 23, 2013 6:34 pm

        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

      Thierry Koblentz

      October 21, 2013 6:45 am

      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

          Thierry Koblentz

          October 21, 2013 1:42 pm

          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

    Sahil Jariwala

    October 21, 2013 3:06 am

    Are classes more preferred over ids?

    0
    • 74

      Andrew Bridge

      October 21, 2013 5:08 am

      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

    Sahil Jariwala

    October 21, 2013 3:13 am

    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

      Thierry Koblentz

      October 21, 2013 8:24 am

      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

        Carlo Rizzante

        October 22, 2013 2:53 am

        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

↑ Back to top