Structuring CSS with the BEM pattern [4d]
We are we 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 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
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.
Look at some examples of a good BEM structure:
- 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.
- 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.
Change the views and CSS of MovieDB so you have a small set of reusable BEM blocks that you can use everywhere.