Better Object Oriented CSS with BEM

by | February 7, 2018 | Website Development

This page may contain affiliate links to recommended products or services. If you choose to purchase after clicking a link, I may receive a commission at no additional cost to you.

Last updated on: April 30, 2023

BEM seems to be all the rage is an industry-standard for front-end developers working with CSS stylesheets.

OOP Organizational Structure for CSS

BEM is an organizational syntax, but it’s also a methodology. It’s not the way to write stylesheet code, but it is a way. I’m sure there is no one right way to BEM your stylesheet, but there are definitely a few ways that work more smoothly than others.

BEM promotes object-orienting your HTML markup and your CSS. It’s often quite a time saver for developers – or yourself – who have to return to a website that was built in the past. It helps programmers who are new to a project understand what stylesheet and front-end template code is doing without requiring too much guesswork.

What does BEM stand for?

Now that you know a few ways BEM can help you compose front-end styling — let’s take a look at what the letters B-E-M stand for.

BEM stands for Block, Element, Modifier.

Blocks are a standalone entity that is meaningful on its own.

Elements are part of a block and have no standalone meaning. Elements are semantically tied to their blocks.

Modifiers are flags used on blocks or elements for changing an element’s appearance or behavior.

Examples of BEM

Okay, so BEM is awesome, but HOW DO YOU DO IT?!

Let’s take a look…

Syntax

First, let’s see an example of BEM CSS syntax:

block__element--modifier

See the B, E, and M? Good.

B – BEM Block Components

Let’s say you want to create markup and styles for a WordPress widget. They’re programmatic, so it’s a good example because you can have lots of different widgets that use nearly identical HTML markup.

Think of this as an opportunity to create a widget block — the B of your BEM component.

<div class="widget"></div>

E – BEM Block Elements

Now, most widgets have a title and content. Add BEM elements to your BEM block called title and content. Title and Content are the E’s to the BEM component.

<div class="widget">
  <div class="widget__title">Widget Title</div>
  <div class="widget__content">
    <p>Hello, world!</p>
  </div>
</div>

Defining BEM CSS Classes

When styling it’s smart keep your CSS flat. Here’s what mine would look like:

.widget { }
.widget__title {}
.widget__content {}

Maybe you’ve added some style properties to those classes too to make titles bold and to make the content 10px away from the title, like so.

.widget {
  border-top: 1px solid #CCC;
  border-bottom: 1px solid #CCC;
}

.widget__title {
  font-weight: bold;
}

.widget__content {
  padding-top: 10px;
}

M – BEM Modifiers

BEM modifiers are for when you want to have a variation of a BEM component.

Imagine the code above works for 4 of 5 sidebar widgets on your website, but the last one is different.

You don’t need to dump the code you’ve already written. Using BEM modifier classes, simply add or append style properties to the existing CSS styles.

Consider a scenario where you want to make a widget with a red background, for instance. You don’t need to create an entirely new widget. In fact, you can keep and repurpose all of the code you’ve already written for the existing widget components.

Let’s look at modifying with BEM.

BEM Class Naming Conventions

First, decide on a class name. Call this .widget–alt or .widget–red, for example. widget–alt is more generic and gives you greater flexibility. If a month from now you decide red was the wrong decision and all of your widgets should really be blue it would be extra work to keep the class names in sync, so generalizing is a good strategy. Class naming is important, but it’s totally up to you.

Modifier Markup

Second, you want to add your new class to the markup.

<div class="widget widget--alt">
  <div class="widget__title">Widget Title</div>
  <div class="widget__content">
    <p>Hello, world!</p>
  </div>
</div>

See how .widget is now .widget.widget–alt?

If you’re using Sass (aka scss), you could @extend .widget into .widget–all. However, I find as convenient as extending can be during the time you decide to use it, it’s often confusing and time-consuming down the road when you return to track down where a style is coming from. I prefer adding a second CSS class to the markup, as shown in the example.

Componentizing Design

BEM forces you to think in components.

Components are a single piece — or function — of a web page.

However, establishing what is and what is not a component is a fuzzy science at best. It’s mostly up to you, but the idea behind this style of modular web development is to define a component as an object, then identify smaller pieces within the component to define those as elements. You end up with a “thing” composed of many smaller “things”. If your component is a car then your elements would be its parts.

Modularization means a greater ability to reuse and repurpose pieces of your styles, so there are layers of benefits.

Conveying Meaning through Syntax

Using BEM, you end up with CSS class names for HTML markup that convey meaning. They provide meaning about each element in relation to the styles being applied, so you can quickly and more easily determine what component an element belongs to.

Simplified Modular Maintainability

For the most part, modular code is easier to update and maintain. Common elements can exist in fewer places. As a result, you benefit by not needing to edit as much when it’s time to make a routine CSS update.

A simple organizational trick for locating stylesheet code faster lies in how you name your CSS class components. As you’re creating BEM classes, be verbose with naming conventions. And at the same time, make your naming conventions match the naming conventions in your website’s CSS style folder structure.

For example, imagine you’re styling a form. You could use the CSS class form customer-contact-form and place styles inside of the directory /styles/forms/customer-contact-form/. Doing so would make it incredibly easy to find and update if you needed to.

Increase Confidence Levels

BEM CSS can increase your confidence level when making stylesheet changes to your website.

For instance, if you keep your CSS flat – at a specificity level of 1 – you can know for certain that the change you want to make will only ever affect that one thing. By specificity level 1, what I mean is that your CSS classes should never be nested. As in, don’t cascade your cascading stylesheet (if you can help it). Kiss nesting-related-styling-issues goodbye. And, say “hello” to clean-looking stylesheets.

If you’re nesting too much it means the organization of the styles in your stylesheet is going awry. In my opinion, if your stylesheet starts to look ugly — when it’s getting “code stink” — something’s gone off-course. You should assess the situation, adapt what you’re doing, and re-align for ease of management.

Intuitive Adaptation

Use a BEM modifier class if you need to change the look of a component or element.

If you’re new to BEM and haven’t thought about how modifier classes work it can seem like a pain. But, I promise BEM modifier classes are totally worth the effort. Knowing you can step back into a website you coded 6+ months ago and make quick changes just as if the code was fresh in your mind from yesterday is a priceless quality.

Next Level CSS Optimization

Combining BEM with other front-end organizational strategies like ITCSS or Atomic Design allows you to really step up your front-end website development game. Optimize development, componentize your front-ends, and create some really cool and easy to repurpose CSS website style guides.

The best part? The best part is you can use BEM CSS with any website you’re working on.

Wrapping Up

Once you’ve got the hang of it, BEM syntax is easy. It helps organize code, promotes organized thought, and creates more all-around CSS efficiency. Using BEM, you’ll work faster with a higher degree of confidence whether.

For a more in-depth look check out this BEM 101 article on CSS-Tricks.

Floyd Hartford is a website developer from southern Maine. He's focused on creating and building WordPress websites and loves spending time digging into code like HTML, CSS, scss, jQuery, PHP, and MySQL.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

14 + 13 =

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

Looking for WordPress Help?

I’m a freelance web developer specializing in small business and corporate marketing websites.

Pin It on Pinterest