Table of Contents
CSS BEM Naming Convention: What It Is, Why It Matters, and How to Use It?
Ahmet Erkan Paşahan ・ Sep 14
Home Web Front-end CSS Tutorial Mastering CSS BEM naming with Practical Examples: Pure HTML, Angular, and Next.js

Mastering CSS BEM naming with Practical Examples: Pure HTML, Angular, and Next.js

Sep 18, 2024 pm 09:15 PM

In the previous article, we explored the basics of the BEM naming convention in CSS and why it's crucial for maintaining clean and scalable code.

This time, we will dive deeper with practical examples to see how BEM works across different environments: Pure HTML, Angular, and Next.js.

BEM is not limited to basic HTML structures; it can be effectively applied in any modern frontend framework. By the end of this article, you'll have a clearer understanding of how to implement BEM in various development setups.

Example 1: Using BEM in Pure HTML

In this example, we’ll create a user profile card that dynamically changes its style based on the user’s online or offline status. This is a common use case in real-world applications where elements need to change based on state or condition.

HTML:

<div class="user-card user-card--offline">
  <img src="profile.jpg" alt="User Avatar" class="user-card__avatar" />
  <div class="user-card__info">
    <h2 class="user-card__name">John Doe</h2>
    <p class="user-card__status">Offline</p>
  </div>
</div>
Copy after login

CSS:

.user-card {
  display: flex;
  align-items: center;
  padding: 15px;
  border: 1px solid #ddd;
  border-radius: 10px;
  background-color: #f5f5f5;
  max-width: 300px;
}

.user-card__avatar {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  margin-right: 15px;
}

.user-card__info {
  display: flex;
  flex-direction: column;
}

.user-card__name {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 5px;
}

.user-card__status {
  font-size: 14px;
  color: #888;
}

.user-card--online {
  border-color: #4caf50;
  background-color: #e8f5e9;
}

.user-card--online .user-card__status {
  color: #4caf50;
}

.user-card--offline {
  border-color: #f44336;
  background-color: #ffebee;
}

.user-card--offline .user-card__status {
  color: #f44336;
}
Copy after login

Explanation:

  • The user-card is the block representing the user profile card.
  • Modifiers like user-card--online and user-card--offline change the appearance of the card based on the user's status.
  • user-card__avatar, user-card__name, and user-card__status are elements of the user-card block representing the avatar, name, and status, respectively.
  • The use of BEM makes it clear which styles apply to the block and which styles change based on the status of the user.

Example 2: Applying BEM in Angular

In this Angular example, we'll create an interactive button that shows a loading state when clicked. This is a frequent use case in forms or interactive elements where the state of the button changes based on user interaction or API calls.

Angular Component (button.component.html):

<button class="button" [ngClass]="{'button--loading': isLoading, 'button--primary': !isLoading}" (click)="handleClick()">
  <span *ngIf="!isLoading">{{ buttonText }}</span>
  <span *ngIf="isLoading">Loading...</span>
</button>
Copy after login

Component Styles (button.component.css):

.button {
  padding: 12px 24px;
  background-color: #333;
  color: #fff;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.button--primary {
  background-color: #007BFF;
}

.button--loading {
  background-color: #666;
  cursor: not-allowed;
}

.button--loading span {
  font-size: 14px;
}
Copy after login

Component Logic (button.component.ts):

import { Component, Input } from '@angular/core';

@Component({
  selector: 'app-button',
  templateUrl: './button.component.html',
  styleUrls: ['./button.component.css']
})
export class ButtonComponent {
  @Input() buttonText: string = 'Submit';
  isLoading: boolean = false;

  handleClick() {
    this.isLoading = true;

    setTimeout(() => {
      this.isLoading = false;
    }, 2000);
  }
}
Copy after login

Explanation:

  • The button block represents the base button.
  • The [ngClass] directive dynamically adds button--loading when the button is in a loading state and button--primary when it’s in its default state.
  • The button’s text changes based on the isLoading state.
  • The handleClick method simulates a loading state and resets it after 2 seconds, representing a typical API call scenario.

Example 3: Implementing BEM in Next.js

In this Next.js example, we'll create a navigation menu that highlights the active page dynamically. This is a common scenario in web applications where the current page needs to be visually indicated in the navigation.

Next.js Component (components/NavBar.js):

import { useRouter } from 'next/router';

export default function NavBar() {
  const router = useRouter();

  return (
    <nav className="nav">
      <ul className="nav__list">
        <li className={`nav__item ${router.pathname === '/' ? 'nav__item--active' : ''}`}>
          <a href="/" className="nav__link">Home</a>
        </li>
        <li className={`nav__item ${router.pathname === '/about' ? 'nav__item--active' : ''}`}>
          <a href="/about" className="nav__link">About</a>
        </li>
        <li className={`nav__item ${router.pathname === '/contact' ? 'nav__item--active' : ''}`}>
          <a href="/contact" className="nav__link">Contact</a>
        </li>
      </ul>
    </nav>
  );
}
Copy after login

Next.js Styles (styles/NavBar.module.css):

.nav {
  background-color: #333;
  padding: 10px;
}

.nav__list {
  list-style: none;
  display: flex;
  gap: 20px;
}

.nav__item {
  margin: 0;
}

.nav__link {
  color: white;
  text-decoration: none;
}

.nav__item--active .nav__link {
  font-weight: bold;
  color: #007BFF;
}
Copy after login

Explanation:

  • The useRouter hook from Next.js is used to get the current route (router.pathname).
  • The nav__item--active modifier is applied dynamically based on whether the current page matches the menu item.
  • The active page is highlighted by changing the text color and making the font bold.
  • The nav__link is an element inside the nav__item block.

Conclusion

Using BEM in your project allows you to maintain consistency and scalability in your CSS, even when dealing with dynamic components and changing states. By leveraging BEM for state management, dynamic class changes, and conditional styling, you can keep your code structured, modular, and easy to maintain.

These detailed examples highlight how BEM can be applied in real-world applications, making it easier to manage complex UI components across different frameworks.

Follow Me for More Updates!

I hope this article helped deepen your understanding of using CSS BEM in different platforms. If you're interested in more articles, practical tips, and insights into web development, make sure to follow me for regular updates. Don’t hesitate to reach out if you have any questions or feedback—I’d love to connect and hear from you!

The above is the detailed content of Mastering CSS BEM naming with Practical Examples: Pure HTML, Angular, and Next.js. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1659
14
PHP Tutorial
1258
29
C# Tutorial
1232
24
Google Fonts   Variable Fonts Google Fonts Variable Fonts Apr 09, 2025 am 10:42 AM

I see Google Fonts rolled out a new design (Tweet). Compared to the last big redesign, this feels much more iterative. I can barely tell the difference

How to Create an Animated Countdown Timer With HTML, CSS and JavaScript How to Create an Animated Countdown Timer With HTML, CSS and JavaScript Apr 11, 2025 am 11:29 AM

Have you ever needed a countdown timer on a project? For something like that, it might be natural to reach for a plugin, but it’s actually a lot more

HTML Data Attributes Guide HTML Data Attributes Guide Apr 11, 2025 am 11:50 AM

Everything you ever wanted to know about data attributes in HTML, CSS, and JavaScript.

A Proof of Concept for Making Sass Faster A Proof of Concept for Making Sass Faster Apr 16, 2025 am 10:38 AM

At the start of a new project, Sass compilation happens in the blink of an eye. This feels great, especially when it’s paired with Browsersync, which reloads

How We Created a Static Site That Generates Tartan Patterns in SVG How We Created a Static Site That Generates Tartan Patterns in SVG Apr 09, 2025 am 11:29 AM

Tartan is a patterned cloth that’s typically associated with Scotland, particularly their fashionable kilts. On tartanify.com, we gathered over 5,000 tartan

How to Build Vue Components in a WordPress Theme How to Build Vue Components in a WordPress Theme Apr 11, 2025 am 11:03 AM

The inline-template directive allows us to build rich Vue components as a progressive enhancement over existing WordPress markup.

PHP is A-OK for Templating PHP is A-OK for Templating Apr 11, 2025 am 11:04 AM

PHP templating often gets a bad rap for facilitating subpar code — but that doesn&#039;t have to be the case. Let’s look at how PHP projects can enforce a basic

Programming Sass to Create Accessible Color Combinations Programming Sass to Create Accessible Color Combinations Apr 09, 2025 am 11:30 AM

We are always looking to make the web more accessible. Color contrast is just math, so Sass can help cover edge cases that designers might have missed.

See all articles