BEM CSS

Introduction to BEM

Cascading Style Sheets (CSS) form the basis of web development when it comes to designing and presentation. As web applications grow in complexity, maintaining a modular and flexible CSS architecture becomes crucial. This is where BEM, known as Block Element Modifier, plays a key role.

What is BEM?

BEM represents a naming system and strategy for constructing efficient and adaptable CSS code. Its purpose is to tackle the challenges associated with styling extensive web applications by emphasizing a modular design approach. BEM divides the user interface into modular components known as "blocks," with each block consisting of distinct "elements" and optional "modifiers."

BEM Basic Concepts

1. Blocks:

These are standalone components found on a webpage, such as headings, navigation menus, or side panels. Modules serve as the fundamental building blocks of the BEM approach. Within BEM, a module represents an autonomous, self-contained section on a webpage. It represents a higher-level structure, like a header, navigation menu, or card. Modules are identified by a simple, descriptive class name, like .header or .card.

Example:

Example

/* Example Block */
.header {
  /* Styles for the header block go here */
}

Naming Convention:

Specify a block by using a unified class name. For example, you can name a navigation bar block as .navbar.

Example:

Example

<div class = "navbar">
  <!-- Block content goes here -->
</div>

2. Elements:

Elements are the components within a block that lack standalone significance. They are semantically linked to the block and are labeled to reflect their purpose within that particular context. Within each block, there exist elements - smaller components devoid of significance or utility beyond the block's context. Elements are denoted by two underscore highlights (__) in the class name.

Example:

Example

/* Example Element within the Header Block */
.header__logo {
  /* Styles for the logo element within the header block go here */
}

Naming Convention:

Use double underscores () to delineate the section from the component. For instance, a component within the header section, akin to a logo, could be labeled as .headerlogo.

Example:

Example

<div class = "navbar">
  <div class = "navbar__logo">
    <!-- Element content goes here -->
  </div>
</div>

3. Modifiers:

Modifiers alter the visual presentation or behavior of a block or element, allowing designers to create different versions without duplicating code. In BEM methodology, modifiers are employed to adjust the appearance or behavior of a block or element, identified by the presence of two dashes (-- ) within the class name.

Example:

Example

/* Example Modifier for the Header Block */
.header--dark {
  /* Styles for the header block with dark theme go here */
}

Naming Convention:

Utilize a pair of hyphens (- - ) to indicate a modifier. If you are using a dark-themed navbar, the modifier class can be designated as .navbar- - dim.

Example:

Example

<div class = " navbar navbar--dark ">
  <!-- Dark-themed navbar content goes here -->
</div>

BEM Structure

BEM provides a clear and structured method for naming classes, simplifying the understanding of relationships among different components for web developers. This approach promotes the reuse of code, decreases the chances of naming conflicts, and facilitates collaboration among team members working on various aspects of a project.

BEM's naming guidelines provide a clear and structured organization to your CSS, simplifying the comprehension of relationships among different components. This clarity becomes crucial in large-scale projects or collaborative environments, reducing naming conflicts and promoting uniformity in code. Adhering to this modular approach enables developers to easily identify and modify specific elements without unintended impacts on other parts of the codebase. Such a methodology lays the foundation for flexible and efficient CSS implementations.

Applying BEM in Your Stylesheet

In your CSS, replicate the BEM format by selecting elements based on their block, element, or modifier classes:

Example:

Example

/* Styles for the Navbar Block */
.navbar {
  /* Block styles go here */
}

/* Styles for the Navbar Logo Element */
.navbar__logo {
  /* Element styles go here */
}

/* Styles for the Dark-themed Navbar Modifier */
.navbar--dark {
  /* Modifier styles go here */
}

Naming Conventions in BEM: Best Practices

While the fundamental principles of BEM involve utilizing blocks, elements, and modifiers, adhering to a set of naming guidelines is crucial to ensuring code uniformity and lucidity. Let's explore some recommended practices related to naming conventions within BEM.

1. Use Hyphens for Modifiers

When naming modifiers, it is recommended to employ hyphens to separate the modifier from the block or element it is modifying. This practice ensures consistency and distinguishes modifiers from elements effectively.

Example:

Example

<!-- Good: Modifier with Hyphen -->
<div class = "button button--large">
  <!-- Button with large modifier styles -->
</div>

<!-- Avoid: No Hyphen for Modifier -->
<div class = "button large">
  <!-- Ambiguous class names can be confusing -->
</div>

2. Keep Selectors Short and Explicit

BEM aims for efficient and streamlined design, therefore, steer clear of unnecessarily long class names. Opt for brief selectors that remain clear and specific to the targeted element.

Example:

Example

<!-- Good: Short and Specific -->
<div class = "header">
  <div class = "header__logo"></div>
</div>

<!-- Avoid: Overly Long Selector -->
<div class = "main-content-section">
  <div class = "content-container-with-padding"></div>
</div>

3. Significant Proper Names

Select names that accurately reflect the purpose and functionality of the block, element, or modifier. This practice enhances code clarity and facilitates collaboration with designers.

Example:

Example

<!-- Good: Descriptive Block Name -->
<div class = "product-list">
  <!-- Block content goes here -->
</div>

<!-- Avoid: Non-descriptive Block Name -->
<div class = "box">
  <!-- Block content goes here -->
</div>

4. Avoid Overuse of Modifiers

While modifiers hold significant power in altering styles or behaviors, their misuse can lead to increased complexity. It is advisable to reserve modifiers for substantial adjustments and instead opt for generating distinct blocks or elements for minor alterations.

Example:

Example

<!-- Good: Limited Modifier Use -->
<div class = "card card--featured">
  <!-- Featured card styles -->
</div>

<!-- Avoid: Excessive Modifiers -->
<div class = "card card--featured card--large card--blue">
  <!-- Too many modifiers can complicate the code -->
</div>

By adhering to these established protocols, you will ensure that your BEM code remains pristine, functional, and easily comprehensible. In the upcoming section, we will delve into the practical aspects of constructing BEM blocks, exploring the methods for creating and designing these essential components in your endeavors.

Creating and Styling BEM Blocks

With a solid understanding of BEM guidelines and naming protocols, let's delve into the practical process of constructing BEM blocks. Blocks serve as the foundational elements of BEM, representing standalone entities within a web page. Below is a step-by-step tutorial on how to create and design BEM blocks efficiently.

Step 1: Identify the Block

Before commencing the coding process, identify the distinct components present on your webpage. These components may include headings, navigation menus, cards, or any other modular sections. Clearly define the purpose of each component to maintain a tidy and well-organized layout.

Step 2: Write the HTML code

Identify the distinct blocks in your HTML code, following the BEM naming convention. For example, if you're designing a navigation bar, your HTML structure might appear as follows:

Example:

Example

<div class = " navbar ">
  <div class = "navbar__logo"></div>
  <div class = "navbar__menu"></div>
</div>

Step 3: Characterize the Block Styles in CSS

In your CSS code, create a section dedicated to block styles. Target the block class and implement the basic styling. Keep in mind that BEM promotes a modular approach, therefore the styles within this block should be tailored specifically for that block.

Example:

Example

/* Styles for the Navbar Block */
.navbar {
  background-color: #333;
  padding: 10px;
  /* Additional block styles go here */
}

Step 4: Style the Elements inside the Block

Next, apply styles to the elements within the block following the BEM naming methodology. Target specific elements and implement the relevant styles accordingly.

Example:

Example

/* Styles for the Navbar Logo Element */
.navbar__logo {
  width: 50px;
  height: 50px;
  /* Additional styles for the logo element go here */
}

/* Styles for the Navbar Menu Element */
.navbar__menu {
  /* Styles for the menu element go here */
}

Step 5: Improve with Modifiers

If you require different styles for your block, utilize modifiers. For example, when creating a darker-themed navbar, introduce a modifier class to define the altered styles.

Example:

HTML:

Example

<div class = " navbar navbar--dark ">
  <!-- Content for the dark-themed navbar -->
</div>
Example

/* Styles for the Dark-themed Navbar Modifier */
.navbar--dark {
  background-color: #000;
  color: #fff;
  /* Additional styles for the dark-themed modifier go here */
}

Step 6: Test and Repeat

Evaluate your block under various conditions to ensure its functionality as intended. If needed, replicate the styles and layout. BEM's structured approach simplifies the process of modifying specific components without impacting the overall design.

Identifying BEM Elements

Before delving into CSS, it is crucial to identify the components within your BEM blocks. Elements are subparts that lack standalone significance and are conceptually linked to their parent block. For example, within a "navbar" block, elements might include "logo," "menu," and "search."

Example:

Example

<div class = "navbar">
  <div class = "navbar__logo"></div>
  <div class = "navbar__menu"></div>
  <div class = "navbar__search"></div>
</div>

Styling BEM Elements in CSS

When styling BEM components, adhere to the BEM naming methodology to maintain a clear and organized layout.

Example:

Example

/* Styles for the Navbar Block */
.navbar {
  background-color: #333;
  padding: 10px;
  /* Additional block styles go here */
}

How about we consider the "navigation bar" block, for example:

Example

/* Styles for the Navbar Logo Element */
.navbar__logo {
  width: 50px;
  height: 50px;
  /* Additional styles for the logo element go here */
}

/* Styles for the Navbar Menu Element */
.navbar__menu {
  /* Styles for the menu element go here */
}

/* Styles for the Navbar Search Element */
.navbar__search {
  /* Styles for the search element go here */
}

By following this approach, each component within the "navbar" section is allocated its individual CSS section, simplifying the process of locating and modifying styles for specific elements.

Advantages of Styling BEM Elements

  • BEM elements keep up with your code's modularity. Every element has its arrangement of styles, making it autonomous and more straightforward to use.
  • By sticking to the BEM naming convention, you maintain clarity in your CSS. It's obvious which styles are for the block and which are for its singular elements.
  • BEM elements can be reused across various blocks, advancing code reusability. For example, a "button" element styled in one block can be effortlessly repeated in another.
  • Modifiers in BEM

Modifiers in BEM play a crucial role in altering the look or behavior of blocks and elements based on different states or variations. They offer a way to generate specific styles without duplicating code, enhancing the flexibility and efficiency of your CSS. Let's explore the practical application of modifiers in BEM.

1. Identifying Modifiers

Modifiers are indicated by a pair of hyphens (--) within the class name. They are used to represent different versions or adjustments to blocks or elements. For instance, envision a block named "button" with a modifier "large". In this scenario, "button" serves as the block, while "button--large" acts as the modifier.

Example:

Example

<div class = "button button--large">
  <!-- Content for the large button -->
</div>

2. Applying Modifier Styles in CSS

In your CSS, create a separate section dedicated to modifier styles. Identify the modifier class and define the customized styles. Building upon the example of "button- - large":

Example:

Example

/* Styles for the Button Block */
.button {
  display: inline-block;
  padding: 10px 20px;
  /* Additional styles for the button block go here */
}

/* Styles for the Large Modifier */
.button--large {
  font-size: 18px;
  /* Additional styles for the large modifier go here */
}

By adhering to this structure, you can effectively manage and update styles for different versions of your blocks or elements. The modifier class restricts the styles to only those relevant to the specified variation.

3. Dynamic Utilization of Modifiers

Modifiers gain significant impact when effectively utilized in relation to user interactions or program conditions. For example, take a "button" component with an "active" state:

Example:

Example

<!-- HTML -->
<div class = "button button--active">
  <!-- Content for the active button -->
</div>
<!-- CSS -->
/* Styles for the Active Modifier */
.button--active {
  background-color: #4CAF50;
  color: #fff;
  /* Additional styles for the active modifier go here */
}

Coordinating BEM with Other CSS Approaches

While BEM stands as a robust methodology independently, it also offers the flexibility to be combined with other CSS approaches to enhance your workflow. Integrating BEM with methodologies such as SMACSS (Scalable and Modular Architecture for CSS) or utility-first frameworks like Tailwind CSS can further boost efficiency and flexibility. Let's delve into the integration of BEM with these alternative methodologies:

1. SMACSS and BEM:

SMACSS revolves around organizing styles into five categories: Base, Design, Module, State, and Theme. BEM can be seamlessly integrated into the Module category, aligning blocks and elements with SMACSS modules.

Example:

Example

/* SMACSS + BEM Integration */
/* Base styles go here */
/* Layout styles go here */

/* BEM Module styles */
.block {
  /* Block styles go here */
  /* Element styles */
  .block__element {
    /* Styles for the element go here */
  }
  /* Modifier styles */
  .block--modifier {
    /* Styles for the modifier go here */
  }
}
/* State styles go here */
/* Theme styles go here */

2. Tailwind CSS and BEM:

Tailwind CSS operates as a utility-first CSS framework. Although distinct from BEM initially, these two approaches can work together synergistically. BEM classes can be employed for complex components, while Tailwind utilities excel at quickly styling simpler elements.

Example:

Example

<!-- BEM and Tailwind CSS Integration -->
<div class = "block bg-blue-500 text-white">
  <!-- Content for the block -->
  <div class = "block__element text-xl font-bold">
    <!-- Content for the element -->
  </div>
</div>

3. OOCSS (Object-Oriented CSS) and BEM:

OOCSS promotes separating structure and style, and BEM aligns effectively with this approach. BEM's blocks handle the structure, with modifiers and elements defining the style. This separation enhances the reusability and modularity of the code.

Example:

Example

/* OOCSS + BEM Integration */
/* Object styles go here */
/* BEM Block styles */
.block {
  /* Block styles go here */
  /* Element styles */
  .block__element {
    /* Styles for the element go here */
  }
  /* Modifier styles */
  .block--modifier {
    /* Styles for the modifier go here */
  }
}

Optimizing Performance

While BEM offers a structured and modular approach to handling CSS, enhancing performance is essential for delivering fast and efficient web interactions. Let's explore some recommended methods for improving the performance of your BEM-based stylesheets.

  1. Minification and Compression:

Minimize and condense your CSS files before transmitting them for deployment. Minification removes unnecessary spaces and comments, while compression reduces the file size. These actions lead to faster loading speeds for your style sheets.

  1. Combining Files:

Consolidate multiple CSS files into a single document. This will reduce the amount of HTTP requests needed to load stylesheets, thereby improving loading speed. Employ build tools or task runners to automate this process.

  1. Simplified Approach CSS:

Identify essential styles needed for initial page rendering and embed them directly in the HTML. This ensures quick loading of fundamental styles, enhancing perceived performance. BEM's structured approach can aid in isolating essential styles for specific components.

  1. Efficient Selector Usage:

Employ potent CSS selectors for pinpointing specific elements. Steer clear of overly broad selectors that could lead to performance and styling issues. The BEM methodology promotes clarity by encouraging precise naming conventions, facilitating the development of targeted and efficient selectors.

  1. Fundamental CSS:

Create a simple CSS for the top section and load it inline. This ensures that the essential styles for the visible portion of the webpage are implemented quickly. BEM's modular architecture enables you to identify and extract fundamental styles for specific components.

Conclusion

The Block Element Modifier (BEM) approach offers a straightforward and adaptable strategy for managing and formatting CSS in web development. In this guide, we have explored the fundamental principles of BEM, delving into its key concepts of Blocks, Elements, and Modifiers. We have observed how BEM's clear and structured naming conventions contribute to code readability, efficiency, and versatility.

From constructing and designing BEM components to managing components within those components, we have provided a step-by-step guide for implementing BEM in your projects. By focusing on practical examples, we have demonstrated how BEM's structured approach enables the efficient styling of various elements, such as menus, card components, and buttons.

Input Required

This code uses input(). Please provide values below: