Posted almost 3 years ago. Visible to the public.

Structuring CSS with the BEM pattern

We are using the BEM pattern ("Block, Element, Modifier") to structure our CSS in all new projects. We try to migrate legacy projects to BEM, block-by-block.

Read

Read the chapter "Taming Stylesheets" from our book Growing Rails Applications in Practice (in our library).

Talk with a colleague about the reasons for the naming conventions we use:

Copy
.block .block--element .block.-modifier

Why are elements preceded by a double dash?

Why is it important modifiers start with -?

Feel the pain

Take two hours and try to change the style of all buttons in the Cards repo:

  • All buttons should have the same background color as before
  • All buttons should be flat (no gradient)
  • Nothing else should look different.

After two hours, take a break and discuss why this change is so hard.

More examples

Look at some examples of a good BEM structure:

Practice: Cards

  • In a new project, try to layout the style of https://makandracards.com/makandra as close as possible.
  • You can use static files, Middleman or Rails for the implementation.
  • Use a number of fake cards so you can layout the grid of cards with real data.
  • Make sure that your implementation uses a clear set of BEM blocks. Blocks like the cards should be reusable for other screens.

Some notes:

  • The actual CSS of makandracards.com is an example for to how not to do it.
  • You are likely to have trouble deciding where to draw the line between the blocks. E.g. a structure could either be two independent blocks or a block that contains two elements. There is not always a right answer to that. Discuss the pros and cons of each approach with your mentor.

Practice: MovieDB

Change the views and CSS of MovieDB so you have a small set of reusable BEM blocks that you can use everywhere.

Owner of this card:

Avatar
Henning Koch
Last edit:
about 1 month ago
by Florian Leinsinger
Keywords:
advanced
Posted by Henning Koch to makandra Curriculum
This website uses cookies to improve usability and analyze traffic.
Accept or learn more