Combining BEM and SMACSS


Code architecture is super important when you want to have clean, readable, and organized code. For small, personal projects, you might be able to get away with just a “hacker” mentality in the sense of just throwing some code together – but that will quickly break down to an unmaintainable state for larger projects. A lot of programming languages have overcome this issue via various frameworks that force some sort of DSL and/or file structure on you (Ruby’s Rails framework is a simple example) – or the language’s paradigm itself allows for clean code architecture (class-based, prototypal, etc.) – but there’s one language devoid of a lot of these niceties that’s ubiquitous across the web and can easily span thousands of lines of code for even the simplest of projects. I’m talking, of course, about CSS.

CSS is about as bare bones of a programming language as you can get; in fact, Wikipedia classifies it as a style sheet language instead of a programming language because it’s practically logic-less. You just select various elements and apply styles to them – and by default the styles will cascade in a particular order based on what selectors you’ve used. That’s it – and like I mentioned earlier, CSS can easily surpass a thousand lines of code for any project! Tools like sass, less, postCSS, and more have helped to add in some neat features to CSS such as mixins, variables, auto-prefixing, and more – but none of those address how you should architect your CSS.

Luckily – several talented developers have begun to tackle this issue, and two CSS design patterns have emerged as the most popular among the crowd: SMACSS and BEM. Now, every design pattern is opinionated to some degree, so you personally have to see if they’re right for you. I started to apply both BEM and SMACSS separately to my CSS-heavy projects and learned what made the most sense for my coding style – and also what I absolutely hated from each design pattern. In the end, I took the core concepts of both BEM and SMACSS and combined them to create a personalized design pattern – and I’m really loving it. It’s helped my CSS organization in such powerful ways, and I want to share with you what I found valuable from each design pattern. Before I do that though, I want to review the core concepts of both BEM and SMACSS – so that we’re all on the same page.

Similarities

Despite the differences, both SMACSS and BEM share a pretty common core set of rules:

  1. Never use ID selectors. CSS class selectors should make up the majority of your styles.
  2. CSS selectors should stay flat – don’t nest them (unless you have a good reason).
  3. Both design patterns focus on a module-based system of organizing the majority of your CSS – which sort of extends how object-oriented CSS (OOCSS) works. What this means is that you should architect your CSS classes in a manner that takes advantage of building repeatable HTML blocks that have a semantic purpose.

Now, let’s get to some of the differences.

SMACSS

SMACSS is a design pattern created by a single developer named Jonathon Snook who works at Yahoo! (which currently implements the SMACSS pattern). It focuses on 5 main types of structures to organize your CSS:

  • Base
  • Layout
  • Module
  • State
  • Theme

Base. Base styles are just that – base styles that apply to base selectors. These should be very simple and incredibly broad styles, such as font color and family, link styles, etc. Something like this:

Easy peasy.

Layout. Layout styles are meant for logic-less container elements that are solely included in your HTML to provide positioning, padding, or other layout-based purposes. By default, SMACSS recommends you begin your layout styles with the l- prefix:

Module. Modules will make up about 95% of the CSS of your page. This topic goes pretty deep – so I encourage you to look up the SMACSS documentation for how modules are intended to work – but the tl;dr version is that you should style a block of HTML code with independent, semantic content as a module with children elements. Something like this:

SMACSS suggests you keep your module names short, so that your child item class names don’t get unnecessarily long. This takes some practice to understand how to style your CSS using a module-based system – but it’s worth the struggle once you feel comfortable with it.

State. States are very simple styles – and are the only time where it’s okay to use the dreaded !important attribute. States are styles that should be triggered by Javascript (i.e. showing an element, hiding an element, marking an element as active, etc.) – and should normally begin with the is- prefix:

Theme. I don’t really use theme styles since my projects typically don’t need them, but their purpose is to provide styles for various themes – where the core styles of a series of pages stay the same, but small things may change like background colors, fonts, etc.

Folder Structure

SMACSS doesn’t place much emphasis on how you should structure your CSS files (which is drastically different from BEM) – so I created my own simple folder structure for the projects where I solely used SMACSS:

Using this as a folder structure, you would just create files for each style type in each respective directory. I use sass in all of my projects, and I’m a very big fan of using sass imports to import every sass file into one core file before I process it as CSS – which is what the app.scss file is.

That covers some of the core concepts of SMACSS – let’s move onto BEM now.

BEM

Compared to SMACSS, BEM is simpler to understand – but it’s much more rigid in how you structure your code and files. In BEM, every style is a part of a module – no base styles, layouts, themes, etc. You just have blockselements, and modifiers. In fact, that’s where BEM gets its name. Here’s a breakdown of what those concepts entail.

Blocks. Blocks are the styles that house related child items. You can think of them as the highest level of a module. Something like a menu:

Elements. Element styles represent the actual child items inside of a block. Elements always begin with the block name, followed by two underscores (__) and a suffixing name:

I like to think of element styles as nouns, since they’re meant as the core styles for actual elements.

Modifiers. Modifier styles are applied to both blocks and elements, and are strictly meant to handle the subtle differences that two similar blocks or elements may have. For example, a menu link may be white – or it may be blue:

Modifier styles always start with the full block or element name, followed by double hyphens (–) and then the modifier name. I think of modifiers as adjectives, since they help to better describe an element or block.

Folder Structure

This is where BEM heavily differs from SMACSS. Where SMACSS didn’t put much emphasis on folder structure, BEM suggests that every single block, element, and modifier should have its own CSS file. So as you start to build out your project, you’ll quickly create detailed file structures like this.

This is very organized – there’s no doubt about that – but to create a new file for every new class basically is a little extreme for me. This was one reason BEM was difficult for me to fully implement in the recommended manner.

So – how do I currently build my CSS? I took the core concepts of BEM and SMACSS and combined them in a way that made sense to me.

Combining Them

I really like BEM’s recommendations with regard to how code blocks should be structured. Blocks, elements, modifiers – building my class names following this design pattern really helped me to think about my code in a reusable block-based manner. I liked it much more than how SMACSS suggested to structure modules – which is practically no structure. However, I don’t feel like everything should be a module – which is BEM’s philosophy. I feel like there’s a valid purpose for base, layout, state, and theme styles – and I don’t feel like they need to be modules.

In the end, I basically went with a SMACSS architecture that leveraged the power of base, layout, and state styles – and instead of SMACSS’ module styles, I substituted them completely with BEM styles – blocks, elements, and modifiers. I also came up with my own file structure that made sense to me:

I kept base, layout, and state styles all limited to single stylesheets because even all together they never grew too large. I created a new file for each block, and kept all modifiers and elements related to that block in the same file. These files usually never grew to beyond 100 lines, so they were very manageable. Finally – I added a config folder for all the files that didn’t translate into direct styles. This config folder would hold things like variables, broad mixins, custom font stylesheets (such as icon fonts), and more.

You can check out a live example of this folder structure in my starter-site template.

Final Thoughts

I mentioned earlier that every design pattern is opinionated – and my personal pattern is no exception. It may appeal to you – or you may hate it, and that’s okay. At the very least, I hope I provided you with a little more knowledge about the two most popular CSS design patterns out there right now, and helped transform some of the opinions you may have had about them. In the end, we all have different coding styles, so one single design pattern won’t fit everyone. The most important obstacle these patterns try to tackle is that of code organization – and as long as you have a methodology behind your code architecture, then you’re good to go – no matter if you use a common design pattern or you just make up your own!

  • Krik Batner

    I have a very similar approach, where I use a combination of the different patterns, the biggest differences though are:

    1. I nest selectors. I want to namespace out my components. So I’ll have .menu, and .menu .menu-item. I rarely ever have to go more than 1 selector deep, but everything for menu should be contained within the .menu class. I also feel like this keeps my HTML cleaner. The only time I go more than one selector deep is if I want to add things like &:hover, etc.

    2. I also keep my states within the components. There are some states that could easily be global such as .hidden, .shown, etc, however I’ve found that each component has different ways of handling the transition between .hidden and .shown, some may fade in, some may slide into view, some may grow, etc, so in my experience it’s better to place these within the component itself.

  • … and your similarities section alone reaffirms my belief that both are nonsense used by people who have ZERO business writing CSS or HTML.

    The whole “never use ID’s” thing — apart from their specificity dominion, they are useful for internal links instead of name on anchor, and scripted targeting, so why not go for triple duty utility instead of pissing another class in there. Much less if you have labels and for attribute like a good little doobie (as opposed to the ignorant jackasses who keep abusing placeholder) you will already have ID’s… so… where does that bit of nonsense even come?!?

    The whole “selectors should stay flat” asshattery is another stunning example of just how mind-numbingly stupid this garbage is. If you’re not “nesting’ them (which is a sloppy inaccurate way of referring to using child selectors) you are basically stuck throwing classes at EVERYTHING, since that’s the only real way to stay “flat” — Congratulations, you’re encouraging people to use two to three times the markup needed and make specificity an even bigger mess than it already is.

    BEM in particular is one of those things that much like brain********, markdown, or even C, reeks of “how needlessly crypyic can we make this”… wait… one underline, two underlines… joe forbid you just use a meaningful WORD…

    Your sample of BEM is a stunning example of how STUPID it is and how you’d end up throwing endless pointless classes at the markup for NOTHING. Since .menu is clearly a list, that would make .menu__item be the LI inside it… WHAT THE **** IS WRONG WITH “.menu li” other than some paranoid unfounded BS claims about “render speed”

    It’s hardly a shock with this type of incompetant ignorant bull we end up with turdpress vomiting up garbage like this:

    Doing the job of this:

    LEVERAGE YOUR SEMANTIC MARKUP!!! EVERY time I come across that level of class-tard bloat in code (such as damned near every Joe blasted turdpress template or anything built with the mind-numbingly idiotic bootcrap) I have the overwhelming urge to introduce my size 9 boot to rectums… and that’s EXACTLY what this “keep the CSS flat” and “use classes for everything” OOCSS style bull actively encourages. HERPA-FREAKING-DERP!!!

    It’s like the garbage that CSSLint is now encouraging or how Google Pagespeed has pissed it’s own bed to now just exist to dupe people into using their rubbish “service” or to shell out for one of the CDN’s their advertisers try to bilk people into using when they really don’t need it.

    … and you can see how mouth-breathingly dumbass said practices are the MOMENT you look at the bloated HTML that results being three to ten times what even the most complex of layouts needs, mated to hundreds of K of CSS spanning a half dozen or more files doing the job of 32k or less in ONE file.

    But to be fair, I say the same thing about all this preprocessor asshattery, which to be brutally frank if you need it, you’re doing something wrong… the laugh being most people’s SCSS being larger than how I’d write the same page WITHOUT SCSS…

    To me all this stuff just results in writing more CSS, more HTML, and doing more work. That’s not working smarter… but when outright scam artist bull like bootcrap and jQuery are the norm, I guess such “work harder not smarter” idiocy is just par for the course.

    Methodologies like these are poster-children for everything WRONG with web development today!

    • alkrauss48

      Now that’s what I call a good response. Much of the current front-end community feels pretty different than you do – and that’s okay. I appreciate you taking the time to give such a detailed response – it’s this type of disagreement that fuels better practices. I’m personally going to stick with these methodologies as far as structuring my styles, as they’ve been super valuable to me in how I semantically think about building my HTML and CSS file structure – but again, that’s me. That obviously doesn’t work for you, and that’s fine – we’re all different. Keep it up Jason!

      • Well, I’m glad you took it in the manner it was offerred — it’s a real counterpoint.

        One part really bugged me that I didn’t touch on:
        “BEM suggests that every single block, element, and modifier should have its own CSS file”

        Unless you’re using a preprocessor to compile all that crap down to a single file, that’s some SERIOUS freaking herpaderp. EVERY separate file on a first-load introduces an extra handshake — there are CSS methods that go at great lengths to reduce the number of overall files for that reason such as the inaccurately named “CSS Sprites”. REALLY if in your finished project you have more than one — MAYBE two — CSS files per media target (screen, print, aural, etc) you have utterly and completely screwed the pooch. More files == 200ms to a second or more real-world average overhead REGARDLESS of connection speeds past the first eight or so files.

        You ever notice that when you upload via FTP it takes longer to upload a hundred separate 10k files than it does a single megabyte sized file? Yeah, that. HTTP does it too. Things like cookies can even increase how long that takes. (hence the whole trick of hosting static files on a separate domain to reduce that overhead).

        … and really, if you have enough CSS on a site to warrant that type of division, there HAS to be something horrifyingly and terrifyingly wrong with either the CSS or the HTML to which it is applied.

        But then IMHO there is little legitimate reason for 90%+ of websites to have more than 48k of CSS for the screen media target for THE ENTIRE SITE. One file. media=”screen,projection,tv”. If you can’t bring it in under that number — without resorting to the whitespace minification garbage — it is entirely likely the methodology is so broken the page is useless to large swaths of users.

        Yes, I realize that bootcrap by itself exceeds that number. Hence why it is unworthy of being referred to by its real name, and why I tell the folks who have been deluded or outright scammed into using it to go find a stick to scrape it off with, before they track it all over their website’s carpets.

        But again I typically use 12k of markup where most people use 60k, and 24k or less CSS in one file where most people use 256k spanning six files. Don’t even get me STARTED about scripttard bloat.

        • seb24

          “Unless you’re using a preprocessor to compile all that crap down to a single file”.
          You obviously use some compiler to get everything in the same file. You have 2 different things here: Dev and publishing. You separate in different files to have better organisation for dev purposes. But you don’t use this as production files. And in general you don’t use FTP anymore.

          • Sadly then, why in blazes do so many sites use a dozen or more separate CSS files? Why do they use hundreds of K of CSS to do two or three dozen’s job?

            Teaching the crappy sloppy bloated practice at the dev stage just teaches making crappy sloppy bloated websites!!! Especially with most “automated tools” doing little more than making the developer the tool.

            As evidenced again by the endless slopped out train wrecks of developer ineptitude that end up wasting megbytes of scripttardery, a hundred k or more CSS, 60 to 100k of markup — all spanning dozens if not hundreds of files — typically to deliver 3k or less plaintext and a dozen or so content images.

            The PINNACLE of herpa-freaking-derp that’s now par for the course in web development. The TRULY screwed up part being that people then defend the practice of using more code and writing two to ten times the code as being “easier”… RIGHT.

            Because doing more work and making it more complex was “easier’.

          • seb24

            I can’t speak with you, it’s just waste of time. You are too agressive and it seem you have only respect for yourself. You don’t understand the big picture but you are so opinionated… It’s just ridiculous.

          • Respect? I just have more respect for the users and visitors to sites than I do the sleazy scam artists who dupe unwitting site owners into screwing themselves over… and the equally sleazy people vomiting up cookie cutter websites that clearly show the creators don’t know the first blasted thing about accessibility, usability, sustainability, calling into question all of their abilities.

            In that traditional “WCAG, what’s that?!?” sort of way.

            Since if the result doesn’t even meet accessibility minimums, and even just pisses off normal users due to being slow, battery wasting, and sending them diving for tools like tampermonkey, greasemonkey, stylish, etc, etc… well, then what good is it?

            But of course that’s one of those harsh truths the sleazy snake oil peddlers don’t want people to know, and the people who’ve been duped don’t want to hear, since it interferes with putting the saddle on people to take them for a ride, or worse points out who’s been saddled up having been made to squeal like a pig like a second rate Ned Beatty!

          • seb24

            You are just a toxic person. The harsh truths ? lol you don’t know most of the stuff you are speaking about… Pitiful.

          • Diego Fortes

            Damn, you’re triggered!

        • seb24

          “LEVERAGE YOUR SEMANTIC MARKUP!!! EVERY time I come across that level of class-tard bloat in code ”
          Do you understand that the example you are giving come from a CMS (WordPress), so an automatic generated content ? It’s not a person in particular writing this but a script generating this automatically. You are a litle bit like Donquichot fighting against Windmill

          • That just further proves the dipshits writing garbage like turdpress don’t know enough about HTML to be creating such systems — made worse by most people using it not knowing enough to fix such glaringly obvious asshattery!

            .. and I assume you mean Don Quixote. I don’t mind the comparison. Frankly someone has to speak out against the hordes of morons, halfwits, and mouth-breathing fools crapping out endless broken slow painful to use websites any-old-damned-way!

            There’s a reason I look upon the state of web development right now with disgust to the point of nausea. After some 38 years of programming — 18 of that dealing with the web, I know stupid when I see it… and DAMN what’s going on right now is pretty damned stupid.

          • Exiige

            Just sounds like you can’t adapt or accept new things, if I was programming for 18 years on the web, I can see how some things may frustrate me.

          • @exiige:disqus Thing is it’s not NEW, in many ways it’s old crap mistakes being repeated… but more than that it’s STUPID. Making it more convoluted, using more code, and more separate files? How is that any EASIER?

            Particularly when in practice it again undoes existing improvements. Kind of like how HTML 5 undoes the improvements 4 Strict made over 3.2 — but what can one expect when people instead of embracing 4 strict just kept sleazing out 4 tranny and now just wrap 5 lip-service around the same outdated, outmoded, 1990’s thinking! There’s a reason it was called “transitional” — aka “in transition from 1997 to 1998 coding practices”.

            It would be like bell-bottoms suddenly being back in style… “oh, no. those are boot-cut” — RIGHT. Major Harris called, he wants his pants back.

            That’s what makes it painful — seeing the same stupid mistakes that have already crapped on things one or more times repeated.

          • Charlie

            Totally with Jason Knight. Exiige and seb24 has a modern look at automated things but in reality, at the end of the day, the designers are on a different layer of the application.

            After us backend devs finish up generating html that is semantically clean with minimal style values in the elements like so

            , it is up to the next person handling the application how to apply styles systematically or however they wish.

            Us backend devs loading html with useless element css classes is a total mess and turd.
            Mess:

          • Exiige

            I don’t get how you go from the 1st example to the 2nd.

            @elementalsjs:disqus More seperate files is obviously easier, you wouldn’t put 2,000 LOC in 1 file and expect to be efficient in changing CSS. In PHP, Ruby or any other language, you don’t shove everything in 1 file… it’s stupid, so why do you think it’s OK to do this in CSS?

            You are backwards, you are living in the past, instead of complaining about a, b, c instead you should embrace the change and go with it. In terms of HTML 4 being better than 5, I can’t really comment as I don’t have a deep understanding of the history of HTML and how various versions got better, but knowing that 4.0 was initially released in ’97, HTML 5 was released 2014. We have only really just begun with HTML 5, there is tons and tons of new things coming as well as improvements being made.

            20 years is a long time for a language to develop, if we had 20 years of development on HTML 5 then we would be infinitely further ahead.

          • Charlie

            If you study html5 and how it works, you wont clutter the html with a ton of css class names. So Jason is not living in the past, he might simply have a better understanding of html. Here is an excellent book to get a grasp on html5 “Introducing HTML5 Second Edition – Remy Sharp and Bruce Lawson”

  • Pingback: hannahpun | SASS+COMPASS 開發初階/進階()

  • Kabahat Önderi

    It’ll be almost perfect, if folder of “vendor” is added to the file structure 🙂