BEM Methodology: A Comprehensive Guide for CSS Organisation šŸŽÆ

beginner
15 min

BEM Methodology: A Comprehensive Guide for CSS Organisation šŸŽÆ

Welcome to CodeYourCraft's CSS Tutorial on BEM Methodology! šŸŽ‰

In this guide, we'll dive deep into the Block, Element, Modifier (BEM) approach to CSS, learning how to write clean, maintainable, and scalable CSS for web projects. Let's get started! šŸš€

Understanding BEM šŸ“

BEM is a naming convention for CSS that helps you organize and structure your styles. It provides a clear and consistent method for defining and managing CSS classes in a scalable and maintainable way.

Block šŸ’”

A Block is the base unit in BEM. It represents an isolated standalone component in your HTML structure. For example, a button, a form, or a header.

html
<div class="button"> Click me! </div>

In the above example, button is the Block.

Element šŸ’”

An Element is a part of a Block. It's a child of the Block and helps describe more specific details about the Block.

html
<div class="button"> <div class="button__text"> Click me! </div> </div>

In the above example, button__text is the Element of the button Block.

Modifier šŸ’”

A Modifier is a special type of element that represents a state or a variation of the Block. Modifiers can change the appearance or behavior of the Block.

html
<div class="button button_state_disabled"> Click me! </div>

In the above example, button_state_disabled is the Modifier of the button Block.

BEM Best Practices šŸ’”

Here are some best practices to follow when using BEM:

  1. Use camelCase for Blocks, Elements, and Modifiers.
  2. Use double underscores __ to separate Elements from Blocks and Modifiers.
  3. Use hyphens - to separate words in Block names.
  4. Avoid using IDs when you can use BEM classes.
  5. Keep your CSS specificity under control by using BEM.

Example: Building a Responsive Button Component šŸ’”

Let's create a responsive button component using BEM.

html
<div class="button button--size-large button--color-primary"> <div class="button__text"> Click me! </div> </div>
css
.button { display: inline-block; padding: 10px 20px; border-radius: 4px; text-decoration: none; font-weight: bold; transition: all 0.3s; } .button--size-large { padding: 20px 30px; } .button--color-primary { background-color: blue; color: white; } .button:hover { cursor: pointer; background-color: lightblue; }

šŸ“ Note: In the above example, we created a large, primary blue button. You can add more Modifiers like button--rounded or button--outline to create different variations.

Quiz: BEM Naming Conventions šŸ’”

Quick Quiz
Question 1 of 1

What is the correct BEM naming convention for an Element of the Block `header` that represents the logo?

Happy coding! 🄳

This guide is intended to be an educational resource and not a comprehensive reference. Continue learning and practicing to master BEM and write better CSS! šŸ’”šŸ’”šŸ’”