290 Structuring CSS with the BEM pattern [4d]

Updated . Posted . Visible to the public.

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:

.block
.block--element
.block.-modifier
  • Why are elements preceded by a double dash?
  • Why is it important modifiers start with -?

More examples

Look at some examples of a good BEM structure in the DOM tree of these websites:

Practice: Cards

  • In a new project, try to layout the style of https://makandracards.com/makandra as close as possible.
    • You only need to re-implement the index view.
    • Implement the view in a state where the user is signed in.
  • 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.

Note

  • You don't need a Rails project for this. Just make a new folder with static HTML and CSS files. You can push it into a new repository in GitLab.
  • Don't peak too much into the actual HTML and CSS of makandracards.com.
  • 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.

Tip

Spreewald can be used with an auto-mapper for BEM classes. You can set it up Show archive.org snapshot for the movieDB and profit from well-named BEM classes in your Cucumber steps.

Henning Koch
Last edit
Henning Koch
Keywords
advanced
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra Curriculum (2015-09-08 16:23)