Decoupling HTML From CSS

Advertisement

For years, the Web standards community has talked about the separation of concerns. Separate your CSS from your JavaScript from your HTML. We all do that, right? CSS goes into its own file; JavaScript goes in another; HTML is left by itself, nice and clean.

CSS Zen Garden1 proved that we can alter a design into a myriad of permutations simply by changing the CSS. However, we’ve rarely seen the flip side of this — the side that is more likely to occur in a project: the HTML changes. We modify the HTML and then have to go back and revise any CSS that goes with it.

In this way, we haven’t really separated the two, have we? We have to make our changes in two places.

Exploring Approaches

Over the course of my career, I’ve had the pleasure and privilege to work on hundreds of different websites and Web applications. For the vast majority of these projects, I was the sole developer building out the HTML and CSS. I developed a way of coding websites that worked well for me.

Most recently, I spent two years at Yahoo working on Mail, Messenger, Calendar and other projects. Working on a much larger project with a much larger team was a great experience. A small team of prototypers worked with a larger team of designers to build out all of the HTML and CSS for multiple teams of engineers.

It was the largest-scale project I had worked on in many aspects:

  • Yahoo’s user base is massive. Mail alone has about 300 million users.
  • Hundreds of people spread across multiple teams were working with the HTML and CSS.
  • We were developing a system of components to work across multiple projects.

It was during my time at Yahoo that I began to really examine how I and the team at Yahoo build websites. What pain points did we keep running into, and how could we avoid them?

I looked to see what everyone else was doing. I looked at Nicole Sullivan’s Object-Oriented CSS2, Jina Bolton’s presentation on “CSS Workflow3” and Natalie Downe’s “Practical, Maintainable CSS4,” to name just a few.

I ended up writing my thoughts as a long-form style guide named “Scalable and Modular Architecture for CSS5.” That sounds wordy, so you can just call it SMACSS (pronounced “smacks”) for short. It’s a guide that continues to evolve as I refine and expand on ways to approach CSS development.

As a result of this exploration, I’ve noticed that designers (including me) traditionally write CSS that is deeply tied to the HTML that it is designed to style. How do we begin to decouple the two for more flexible development with less refactoring?

In other words, how do we avoid throwing !important at everything or falling into selector hell?

Reusing Styles

In the old days, we wrapped font tags and applied background attributes to every HTML element that needed styling. This was, of course, very impractical, and thus CSS was born. CSS enabled us to reuse styles from one part of the page on another.

For example, a navigation menu has a list of items that all look the same. Repeating inline styles on each item wouldn’t be practical. As a result, we begin to see CSS like this:

#nav {
   margin: 0;
   padding: 0;
   list-style: none;
}

#nav li {
   float: left;
}

#nav li a {
   display: block;
   padding: 5px 10px;
   background-color: blue;
}

Sure beats adding float:left to every list item and display:block; padding:5px 10px; to every link. Efficiency, for the win! Just looking at this, you can see the HTML structure that is expected:

<ul id="nav">
   <li><a href="/">Home</a></li>
   <li><a href="/products">Products</a></li>
   <li><a href="/contact">Contact Us</a></li>
</ul>

Now, the client comes back and says, “I want a drop-down menu to appear when the user clicks on ‘Products.’ Give them easy access to each of the pages!” As a result, our HTML changes.

<ul id="nav">
   <li><a href="/">Home</a></li>
   <li><a href="/products">Products</a>
      <ul>
         <li><a href="/products/shoes">Shoes</a></li>
         <li><a href="/products/jackets">Jackets</a></li>
      </ul>
   </li>
   <li><a href="/contact">Contact Us</a></li>
</ul>

We now have a list item within a list item, and links within it. Our menu has a horizontal navigation when the client wants a vertical list, so we add some rules to style the inner list to match what the client wants.

#nav ul {
   margin: 0;
   padding:0;
   list-style:none;
}

#nav li li {
   float: none;
}

#nav li li a {
   padding: 2px;
   background-color: red;
}

Problem solved! Sort of.

Reducing The Depth Of Applicability

Probably the most common problem with CSS is managing specificity. Multiple CSS rules compete in styling a particular element on the page. With our menu, our initial rules were styling the list items and the links in the navigation and the menu. Not good.

By adding more element selectors, we were able to increase specificity and have our menu styles win out over the navigation styles.

However, this can become a game of cat and mouse as a project increases in complexity. Instead, we should be limiting the impact of CSS. Navigation styles should apply to and affect only the elements that pertain to it, and menu styles should apply to and affect only the elements that pertain to it.

I refer to this impact in SMACSS as the “depth of applicability6.” It’s the depth at which a particular rule set impacts the elements around it. For example, a style like #nav li a, when given an HTML structure that includes our menus, has a depth of 5: from the ul to the li to the ul to the li to the a.

The deeper the level of applicability, the more impact the styles can have on the HTML and the more tightly coupled the HTML is to the CSS.

The goal of more manageable CSS — especially in larger projects — is to limit the depth of applicability. In other words, write CSS to affect only the elements that we want them to affect.

Child Selectors

One tool for limiting the scope of CSS is the child selector (>). If you no longer have to worry about Internet Explorer 6 (and, thankfully, many of us don’t), then the child selector should be a regular part of your CSS diet.

Child selectors limit the scope of selectors. Going back to our navigation example, we can use the child selector to limit the scope of the navigation so that it does not affect the menu.

#nav {
   margin: 0;
   padding: 0;
   list-style: none;
}

#nav > li {
   float: left;
}

#nav > li > a {
   display: block;
   padding: 5px 10px;
   background-color: blue;
}

For the menu, let’s add a class name to it. This will make it more descriptive and provide a base for the rest of our styles.

.menu {
   margin: 0;
   padding: 0;
   list-style: none
}

.menu > li > a {
   display: block;
   padding: 2px;
   background-color: red;
}

What we’ve done is limited the scope of our CSS and isolated two visual patterns into separate blocks of CSS: one for our navigation list and one for our menu list. We’ve taken a small step towards modularizing our code and a step towards decoupling the HTML from the CSS.

Classifying Code

Limiting the depth of applicability helps to minimize the impact that a style might have on a set of elements much deeper in the HTML. However, the other problem is that as soon as we use an element selector in our CSS, we are depending on that HTML structure never to change. In the case of our navigation and menu, it’s always a list with a bunch of list items, with a link inside each of those. There’s no flexibility to these modules.

Let’s look at an example of something else we see in many designs: a box with a heading and a block of content after it.

<div class="box">
   <h2>Sites I Like</h2>
   <ul>
      <li><a href="http://smashingmagazine.com/">Smashing Magazine</a></li>
      <li><a href="http://smacss.com/">SMACSS</a></li>
   </ul>
</div>

Let’s give it some styles.

.box {
   border: 1px solid #333;
}

.box h2 {
   margin: 0;
   padding: 5px 10px;
   border-bottom: 1px solid #333;
   background-color: #CCC;
}

.box ul {
   margin: 10px;
}

The client comes back and says, “That box is great, but can you add another one with a little blurb about the website?”

<div class="box">
   <h2>About the Site</h2>
   <p>This is my blog where I talk about only the bestest things in the whole wide world.</p>
</div>

In the previous example, a margin was given to the list to make it line up with the heading above it. With the new code example, we need to give it similar styling.

.box ul, .box p {
   margin: 10px;
}

That’ll do, assuming that the content never changes. However, the point of this exercise is to recognize that websites can and do change. Therefore, we have to be proactive and recognize that there are alternative elements we might want to use.

For greater flexibility, let’s use classes to define the different parts of this module:

.box .hd { }  /* this is our box heading */
.box .bd { }  /* this is our box body */

When applied to the HTML, it looks like this:

<div class="box">
   <h2 class="hd">About the Site</h2>
   <p class="bd">This is my blog where I talk about only the bestest things in the whole wide world.</p>
</div>

Clarifying Intent

Different elements on the page could have a heading and a body. They’re “protected” in that they’re a child selector of box. But this isn’t always as evident when we’re looking at the HTML. We should clarify that these particular hd and bd classes are for the box module.

.box .box-hd {}
.box .box-bd {}

With this improved naming convention, we don’t need to combine the selectors anymore in an attempt to namespace our CSS. Our final CSS looks like this:

.box {
border: 1px solid #333;
}

.box-hd {
margin: 0;
padding: 5px 10px;
border-bottom: 1px solid #333;
background-color: #CCC;
}

.box-bd {
   margin: 10px;
}

The bonus of this is that each of these rules affects only a single element: the element that the class is applied to. Our CSS is easier to read and easier to debug, and it’s clear what belongs to what and what it does.

It’s All Coming Undone

We’ve just seen two ways to decouple HTML from CSS:

  1. Using child selectors,
  2. Using class selectors.

In addition, we’ve seen how naming conventions allow for clearer, faster, simpler and more understandable code.

These are just a couple of the concepts that I cover in “Scalable and Modular Architecture for CSS7,” and I invite you to read more.

Postscript

In addition to the resources linked to above, you may wish to look into BEM8, an alternative approach to and framework for building maintainable CSS. Mark Otto has also been documenting the development of Twitter Bootstrap, including the recent article “Stop the Cascade9,” which similarly discusses the need to limit the scope of styles.

(al) (il)

Footnotes

  1. 1 http://www.csszengarden.com/
  2. 2 https://github.com/stubbornella/oocss/wiki
  3. 3 http://vimeo.com/15982903
  4. 4 http://www.slideshare.net/nataliedowne/practical-maintainable-css
  5. 5 http://smacss.com/
  6. 6 http://smacss.com/book/applicability
  7. 7 http://smacss.com/book/
  8. 8 http://bem.github.com/bem-method/pages/beginning/beginning.en.html
  9. 9 http://www.markdotto.com/2012/03/02/stop-the-cascade/

↑ Back to topShare on Twitter

Jonathan Snook writes about tips, tricks, and bookmarks on his blog at Snook.ca. He has also written for A List Apart, 24ways, and .net magazine, and has co-authored two books, The Art and Science of CSS and Accelerated DOM Scripting. Snook currently works on the design team at Shopify.

Advertising
  1. 1

    Rafael Corrêa Gomes

    April 20, 2012 6:35 am

    Very Cool!

    0
  2. 2

    These are some very well written thoughts but I am a bit fuzzy as to your logic for adding the class ‘hd’ and ‘bd’. Why not just target those as their actual elements instead of adding classes? Is this forethought to the re-usability issues of the class ‘box’?

    0
    • 3

      It has to do with flexibility. I could just target the elements and do “.box ul, .box p” as mentioned in the article. But then the client comes back and says there needs to be a box with two paragraphs? So then you wrap the paragraphs in a DIV. Well, “.box p” isn’t going to work anymore so you go back and wrap the other P in a DIV, even though you didn’t really need to but only because you have to have the CSS to match.

      In other words, you’ve bound the CSS so directly to the existing HTML structure that the moment the HTML structure changes, you need to revisit the CSS or even change the HTML in other areas. You end up doing 3 times the work just to add a new component to the site. Whereas the class avoids this. I can create a new box module on the page and rely on the classes to style things appropriately.

      0
      • 4

        Hmm, *Scratches head*

        I still don’t understand why you wouldn’t just target the elements inside the parent instead of targeting a class inside of a parent element. I realize the specificity is different but in this instance it does exactly the same thing and presents the same problem you outlined with the previous method.

        If the client needed a box with 2 paragraphs then the example would still work fine with out adding any extra DIVs.

        and “.box p” would still work for any P inside the element .box so that wouldn’t need to change either, even if you had to add extra wrapping DIVs. Unless you use the child selector in “.box > p”

        And isn’t using the child selector even more dependent on the HTML structure?

        Generally, when I am coding I try to think ahead. “how can I code this to ensure it’s as flexible and reusable as possible.”

        I understand the reason/need to separate html from everything that makes total sense, but by nature isn’t CSS directly dependent on your HTML? If you have a specific site with specific things on it, your CSS is going to have rules for those specific things.

        I kind of feel as though this is like trying to decouple the paint from a house so that when you add an addition your paint can be moved and reapplied…?

        Maybe I am missing something?

        0
        • 5

          Maybe taking it to an extreme will help highlight the problem. Why use classes at all? You know your HTML structure and can plan for that. Maybe a little “aside > div:nth-child(2) p” will solve the problem. Client wants something different? Just modify the selector.

          But trying to manage a project like this would be hell.

          Similar to your analogy, you’re looking to custom design something for every room. Any changes to the room or additions to the room require custom alterations. Custom cabinets for every room are lovely but would be a pain to alter every time. I’m suggesting to create a reusable piece. Have a new room to build? Reuse the existing cabinets.

          (I understand that even this analogy is a stretch. I dislike analogies! ;))

          0
          • 6

            Jonathan, I think there are situation, when you better should use html tags than classes in your CSS. Imagine you are developing a template for a CMS and want to define the headings for the right column of the template. You could do this by defining “.h1-right-column {…}” in your CSS – but then you would also need to change the CMS to output the header-tags with this class. As some CMSs use RTEs and are allowing headers in the RTE text, this can be really anoying to accoumplish. I guess it’s more easy to just define it as “.right-column h1 {…}”.

            0
          • 7

            You know, sometimes I become so frustraded with the modifications from a client that I want to place all the styles inline.. usually I decline immediatly such thing, but sometimes the frustration is so high and the deadlines so near that I feel really tempted to do so.

            0
        • 8

          stephen murdoch

          April 21, 2012 7:19 pm

          O’Ryan, targeting classes makes sense, if you think about it. Imagine you want five different boxes, where the main payload, (ie. the stuff inside the box-bd class) is delivered through a different html element each time (perhaps a “p” tag in the first box, a “ul” in the second, a “blockquote” for the third, an “address” element in the fourth and then a “code” element for the fifth.) Instead of targeting all 5 different elements, you can just target one class, “box-hd” and apply that class to each element in the markup.

          0
          • 9

            This will be a little off topic, but I’d still like to state it. We probably agree that it’s a good thing to make your html as descriptive, semantic as possible. Using fewer classes can force you to write better html, I believe. Classes are great for doing complex js things, but for styling you do not, actually, need them (IF we can rely on css3).

            Stephen has a very valid point about possible redundancy in your selectors, but probably just a few kb on very large css files. The other point is the sustainability, having to write and alter all these selectors.

            But there are solutions to that. SASS:(http://sass-lang.com/) is one (this is where I go off topic), allowing the nesting of selectors and compiling these into css. This way, it’s easy to change the selector chain, because when some element is added or changed, you can just add that extra layer in the stack. An other plus is that both the html and the compiled css are very descriptive.

            0
          • 10

            Assuming that you’ll always have a .box-hd and that you don’t know how many box-bd there will be, I don’t think this is the best approach. What if you had a huge .box with 40+ box-bd(s). You have to go back to the HTML and add that class manually to every element.
            Why do that when you can do something like:
            .box-hd ~ *{ margin:10px; }

            The box-bd class is not useful at all, IMO.
            Great article!

            0
      • 11

        This makes total sense to me but what happens with a CMS that the client manages? How would you handle adding a class name to every ‘p’ element that gets dropped into the content? I couldn’t imagine telling my client to add a class name to every ‘p’ element that gets dropped into the content. jQuery is probably not the best way to scout for ‘p’ elements that get dropped into boxes with certain class names either.

        0
        • 12

          Dealing with unknowledgeable clients is always difficult. Does the client know to always enter a P element? What if they accidentally put in more than one? What if they unknowingly (or knowingly) put in a blockquote or a div? How do you plan for those eventualities?

          The more flexible a system is in letting a client manage, the less control over you have over the result and I don’t know of any methodology or technology that can solve that. :)

          0
          • 13

            Scott Richardson

            April 21, 2012 4:26 pm

            When we build our CMS’s we don’t give the client much in the way of styling controls. They enter straight text. However we could then have the PHP automatically convert new lines to paragraphs with the associated classes applied to them.

            0
        • 14

          I don’t think we should provide any html level access to clients. They may harm their websites unknowingly.

          Style control can be provided to them where they may select different styles from select boxes.

          0
        • 15

          This tool looks amazing. I know basic css, but I have ayalws been a little intimidated to learn enough to create an entirely table-less design.

          0
        • 17

          Training your client on how to maintain the CMS and add content should be part of the scope of the job, not just designing the site and walking away. This might not always be possible due to budget constraints, but it should definitely be part of our plan.

          0
    • 18

      I’m on the fence regarding this, I can see both sides & my work method has tended to go the same way as Daniel is describing.

      However, I can see the merit in the approach of being overly specific with classes – going back to more verbose methods, as I’ve got into the habit of stripping everything to the bare minimum.

      In the case of your box example, it’s clear that the text elements within it are intended to be used outside of that box, otherwise there’s not much point in adding classes to them. They are therefore effectively generic text classes – and would probably go in a text section in a css file, or within an individual text less or sass file.

      Therefore I get where your coming from – and perhaps the example shouldn’t be taken so literally, as it’s a simple example.

      0
  3. 19

    , Can we have Video presentation for this . which will be beneficial. sometime while doing we may end up changing other coding (newbies), so video tutorials will be a +1

    0
  4. 21

    Joseph Szymborski

    April 20, 2012 7:05 am

    Very interesting article. What’s particularly cool about this is that it juggles both redundancy in the html as well as dependance on the CSS. I mean its easy to solve the first with css and the second by omitting css, but you describe a methodology that is simple and acheives both. Thanks! This is something I’ll be using in my work.

    0
  5. 22

    Very interesting… However, I’m surprised there are no references to HTML 5 elements. Anyway still very useful.

    Thank you.

    0
    • 23

      That’s one of the great things about approaches like this: it doesn’t really matter what elements you’re using. If you want to replace a bunch of divs with articles and sections, your css will still work.

      0
      • 24

        The article and section elements aren’t really designed to be used interchangeably with divs and they’re not even meant to be styled. Article should be used to encapsulate content that can be viewed separately from the rest of the website and still make sense, whereas section should be applied to content that has an underlying theme but wouldn’t make sense outside of the surrounding content.

        Either way it specifically mentions not to use those elements for style purposes in the specifications.

        0
        • 25

          The spec says not to use them solely for styles, but only when semantically appropriate. They are absolutely viable for styling and should be used that way.

          An article or section is not interchangeable with a div, but oftentimes something that would be marked up as a div in xhtml should be an article or section in an html document.

          0
          • 26

            Sebastian Starke

            May 6, 2012 4:39 am

            Older Internet Explorers ignore section and article. If I want my site to behave the same way in every browser, I have to add extra divs for styling. So why should I want to use HTML5 Elements for styling?

            (Sorry, if this is a dumb question.)

            0
      • 27

        Sebastian Starke

        April 21, 2012 12:30 am

        That was very interesting. I definitely will read your book. Thank you very much.

        0
        • 28

          Sebastian, you can use Modernizr.js to detect for older versions of IE, and use polyfill Javascript found on the Modernizr page to make old IE respond to those.

          What I do is use HTML5 elements, but attach CSS classes to them such as and style the page that way. No problems.

          0
  6. 29

    Have it, reading it and learning lots! Worth a purchase in my opinion.

    0
  7. 30

    Great article!

    By the way, what themes are you using on your code editor in the thumbnail pick?

    0
  8. 33

    Thank you very much for good explanation. I’m using scoping with child selectors in heavy-weight projects since about 2009. I find it specially effective, if used combined with SASS or LESS preprocessors and a container / component building methodic (to keep your selectors not too long, if building deep-nested components). Useful to reduce dramatically number of bugs made due to rewriting some styles you were unaware of, too.

    0
    • 34

      I am SO happy I found {LESS}.

      Til that day I could never organize my CSS in a way that was easy to find and well-structured. Though it requires either JS-enabled on the client or support for server-side processing, I LOVE how easy it is to implement. Variables alone in CSS is a great feature, and there’s plenty more than that which LESS offers.

      0
  9. 35

    Thanks for your insight, mate

    0
  10. 36

    First, I have to say that 95% of the code I write these days is for CMS theming. So I’ve had to find ways to work with flexible content. Instead of adding a class to the inner elements, or targeting the inner elements at all, I nest a div inside for padding (like we used to do for handling the inconsistent padding behavior of browsers). The majority of the time this works. The only time it doesn’t is if I need to add a border below an element that creeps into the padding area. Then I add padding and negative margins to that element.

    Like all of us, I’ve had my share of projects where I’ve felt as if I was having to be so specific with elements that I was writing a separate set of styles for every page, and sometimes I probably have. But that comes down to the design part of the project, not the front end code.

    Currently, I’ve been using LESS and I’ve found that it has helped immensely with efficiency and organization.

    0
  11. 37

    Very good concept. I really like this clean CSS and HTML approach. Great for Enterprise HTML5 application.

    0
  12. 38

    Great article! I’ve heard about creating a more object oriented css before but I don’t think I ever truly understood what they were talking about. This article clarified a lot of things!

    0
  13. 39

    Let’s be honest, CSS will always be tied to the HTML. This is not like a piece of server side code where you will swap out a particular database for another.
    Utilizing classes instead of tag based selectors should be pretty common knowledge if you’re looking to reuse portions of your CSS. That said in some cases tags may be more appropriate. Even if your HTML changes you are only going to need to change small amounts of your CSS, which really isn’t a big deal at all.

    Never understood why Smacss and Oocss get so much coverage, or even workshops about them… CSS is not rocket science people!

    0
    • 40

      And yet, I’ve seen projects with CSS that is a complete mess. I’ve had to refactor HTML and CSS across an entire project just to clean it up. I’ve had to resort to adding !important to solve specificity problems.

      What I’ve found is that by following the methodology that I describe here (and in the book and in the workshop), I have a project that’s easier to manage and, even better, results in less code.

      0
    • 41

      Where I work we have a 17,000 page site. There has been no method/architecture to the way we write CSS beyond some basic desicions made 5 years ago about using seperate .css files. We badly need a solid principled approach to the design of the CSS architecture, and we have to be able to implement it as quickly as possible (remember this has to work over 17,000 pages) this is exactly the kind of idea we need to solve this rather hairy problem.

      0
  14. 42

    Great tutorial.Really nice.

    0
  15. 43

    There’s always room for disagreement, of course. I saw an article *somewhere* online suggesting that “less is more”, and advocating toward compact CSS with less (what the article called) “class-itis”. On most of my client sites, I get away with no classes and the CSS remains (over the years) rather compact. This is done with careful use of CSS selectors (including such things as [href="something"] and common pseudo-selectors.

    0
  16. 44

    While I agree with the use of child selectors. I have to partially disagree with your use of classes. It just adds too much bloat to the html. These are things that could (and should in most cases) be handled through selectors and child selectors.

    The last thing you want is a bigger than necessary html file with a case of classitus.

    0
  17. 45

    I think it’s great to modularize code, but if we want maintainable and flexible code, we need to be using CSS as it was intended. Once we start requiring classes on everything, we’re actually going back to the problem of having HTML tied to the CSS. What if someone forgets to add the class? The design will break. What if we pull in plain old semantic html from another source? We can’t, and we lose the flexibility to do so.

    0
    • 46

      HTML is very limited when it comes to semantics. Classes help provide more context and increase semantics. That’s why they’re there. What if someone forgets to add a class? What if they forget to add semantic HTML? What if they forget to add valid HTML? Things break.

      I respect that what is described here sounds like a simplification of CSS development and is heading in the opposite direction of what CSS is giving us the power to do but as projects grow, this simplification is the direction that the industry is heading as seen by the likes of BEM, OOCSS, Google Page Speed recommendations, Twitter Bootstrap, and others.

      0
  18. 47

    I’ve found that using child selectors is generally the best way to build CSS that can be reliantly changed and also help you write a hell of a lot less. For example, the trusty ol’ Suckerfish menu. You can get it to be so efficient with using child selectors that it’s ~100 lines and accounts for all possibilities, including infinite sub-menu drop downs.

    Since we’re already using child selectors, we may as well stack classes in CSS rather than making a new class altogether.

    .box.hd would probably make it a little more modular and repeatable, but they pretty much do the same thing anyway.

    Great article, Jonathan!

    0
  19. 48

    Jonathan, great article, I have been using SMACSS for a few months now and have made it my default CSS methodology. I am sure I am not doing things 100% as you have outlined them but each re-factor of my CSS brings me a bit closer.

    Question: I am working on a mobile website and am creating buttons using CSS3 gradients and borders. The CSS for these buttons is quite extensive (different types of buttons, etc). So I started prefixing my button CSS with “b-”. Would you suggest that extending the SMACSS methodology in this way a correct path? Using the “b-” prefix really helps me to identify and work with the button code I have created.

    0
    • 49

      Yes, I believe this to be a perfectly reasonable approach. It’s a simple prefix and as long as everybody on the team knows that b- is a button then it’s all good.

      0
  20. 50

    for CSS is bluePen CSS Editor the best
    view under http://www.bluepeneditor.com

    0
  21. 51

    Yes, child selectors, agree on that one.

    Using classes for every single HTML piece? I don’t think this method is for me or for how I work with off-shore folks who already have quite a hard time with plain, vanilla HTML. Having them deal with classes for every single HTML element would be a development catastrophe.

    Nonetheless, it’s quite interesting to see this method work in Yahoo teams.

    Thanks for the article.

    0
    • 52

      I don’t necessarily recommend using classes for every single HTML element. I recommend using classes in situations where the HTML element that might be used could vary. For example, having a navigation with .nav and adding .nav-item to every other LI would seem really superfluous and I would shy away from doing this.

      0
  22. 53

    It all depends on the scale of project. For the CSS Zen Garden like projects I would again consider writing good, semantic markup and css that refers also to elements itself or other attributes. For larger projects that needs to be maintainable your approach looks nice and it`s the right way to go, imho.

    One question: I like the idea of simplifying things and use i.e. ID attributes for JS and class attributes for CSS only. However, I predict that for large scale projects that changes very often and many developers (newcomers) work on it (like corporation websites that base on one system) problem with names may appear. Class name that was ones used for module which is currently disabled or forgotten/not used can be used for new written piece of code. At some point someone decides to enable old module and kittens die :(
    It often happens in projects that based on one, large system with tons of modules that can be enabled or disabled, and documentation is often not up-to-date or doesn`t exist at all. At least I have such experience. I know that real problem lies elsewhere like in project management but such things often plays main role when you or team decides which coding standard to pick for a project to solve such issues.
    Have you ever encountered something like this?

    Great read btw.
    Thanks.

    0
  23. 54

    My main concern with this approach is “classitis”. The question is, when do we stop adding classes to the elements? Do we add a class for every single element. What happens when a client wants .box 1 to have a blue background and .box 2 to have a gray background and .box 3 to have a green background. Then we need to add more classes. It seems to me that it’s still going to be a constant back and forth of adding classes and modifying style sheets.

    As someone else mentioned, I have to work with people who are not familiar with HTML and CSS and yet have to produce HTML and CSS. It’s necessary in those cases to have a very well defined module format, taxonomy, and enforce specific structures at every step of adding content. As soon as we open it up to these developers and users to start adding their own classes without a rigid set of rules and reasons we get classes like “red_bold_small_left” and “box_nav_li_a” and we get a div wrapping a tr or li.

    I like the idea of decoupling, but typically decoupling works when the two parts can function independently from one another and can be swapped for other similar components. I don’t really see CSS being able to work independently from HTML, or being able to swap my CSS to any other site. I can’t use it with anything but HTML and there’s no single module format or set of content descriptors that covers the range and variety of content that can be created.

    What I see here is defensive coding and edge case development. It’s like a development project where a client asks for features that customers aren’t demanding (yet) in the hope that someone might need something somewhere, maybe, way down the line. That’s a very non-agile approach. Additionally I’m concerned about code bloat at a time when bandwidth for mobile devices is becoming a concern again. While adding .box-hd makes it clearer that this .hd is in a .box it’s also adding extra bytes solely for readability, when we have tools that will help us understand those associations and their complexity much more readily (e.g. Firebug, IE & Chrome Developer Tools, etc.)

    0
  24. 56

    TL;DR: The classes approach works out best, also doesnt interfere with JS, as you will find that most JS guys gonna tell you that IDs are for JavaScript, classes are for styling.

    WP has adapted the use of body classes, which, combined with HTML5-html classes, help you to get your code easily adaptable, and even more: universally portable.

    What you should also use – and what isnt mentioned in this article – is the use of multiple selector classes (don’t know if its the correct term), like this:
    .box {
    border: 1px solid #333;
    background-color: #eee;
    }

    .box.type-post {

    background-color: #fdd;
    border-color: #666;
    }

    So you’re enabled to create variations of that base class, which could be also differently styled if combined with another base class (eg. .inline-box.type-post).

    cu, w0lf.

    ps: proper code formatting with the code tag or some shortcode stuff would help these examples A LOT.

    0
  25. 57

    Gustaff Weldon

    May 6, 2012 12:38 am

    Thanks for the good read.
    Are there any sites which currently use either SMACCS or OOCSS, that you would recommend as examples wort looking into?

    You’ve given some examples, but I’d love to learn from real world markup and styling. The bigger the site, the better.

    When you learning, you are likely to encounter problems someone has probably already solved. Having existing site to learn from helps immensly.

    0
  26. 58

    I was already doing SMACSS without knowing it then! WordPress themes often use classes for modules of content such as .menu, .widget / .widgettitle / .widget-wrap…

    0
  27. 59

    true story ^^

    0
  28. 60

    I just posted my experience with using LESS and Bootstrap together – http://blog.appliedis.com/2013/02/04/bootstrap-with-less/

    0
  29. 61

    Good article on a touchy subject (as every designer has their favorite and inviolate “tool set”). LoL More amusing is that lately, the “simplification solution” (aka, CSS) is usually 10X more code than the original HTML file, and requires orders of magnitude more “tweaking” than HTML ever did. Oh what webs we weave when we set out to obfusicate! (with apologies to Will). LoL

    0
  30. 62

    So far I like it. Not dissimilar from what I am doing already. Surely I can do even better ;)

    Thanks for sharing.

    0
  31. 63

    The hours and hours you are saving so many of us is mind boggling… This is an enormous “Aha!” moment for those who are taking the time to apply SMACSS methods to their CSS. I must say, it is slower going during initial developing stages, but worth it’s weight in Platinum. I assume, like anything, it becomes more automatic with practice. I’ll get there.

    0

Leave a Comment

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

↑ Back to top