Table of Contents
丑极了!
用还是不用BEM?
Home Web Front-end JS Tutorial Detailed explanation of BEM syntax

Detailed explanation of BEM syntax

Mar 19, 2018 am 10:01 AM
Detailed explanation grammar

This time I will bring you a detailed explanation of BEM syntax. What are the precautions when using BEM syntax? The following is a practical case, let's take a look.

BEM means block, element, and modifier. It is a front-end naming methodology proposed by the Yandex team. This clever naming method makes your CSS classes more transparent and meaningful to other developers. BEM naming conventions are more strict and contain more information, and they are used by a team to develop a large and time-consuming project.

It is important to note that the BEM-based naming scheme I used was modified by Nicolas Gallagher. The naming technique described in this article is not the original BEM, but it is an improved version that I prefer. Regardless of the actual notation used, they are all based on the same BEM principles.

The naming convention pattern is as follows:

.block{}.blockelement{}.block--modifier{}
Copy after login
  • .block represents a higher level abstraction or component.

  • .blockelement represents the descendants of .block and is used to form a complete .block as a whole.

  • .block--modifier represents different states or different versions of .block.

The reason you use two hyphens and an underscore instead of one is so that your own blocks can be delimited with a single hyphen, like this:

.site-search{} /* 块 */.site-searchfield{} /* 元素 */.site-search--full{} /* 修饰符 */
Copy after login

BEM The key is that the name alone can tell other developers what a certain tag is used for. By browsing the class attribute in HTML code, you can understand how modules are related: some are just components, some are descendants or elements of these components, and some are other forms or modifications of components. symbol. Let's use an analogy/model to think about how the following elements are related:

.person{}.personhand{}.person--female{}.person--femalehand{}.personhand--left{}
Copy after login

The top-level block is 'person', which holds some elements such as 'hand'. A person will also have other forms, such as a female form, which in turn will have its own elements. Below we write them as 'regular' CSS:

.person{}.hand{}.female{}.female-hand{}.left-hand{}
Copy after login

These 'regular' CSS are meaningful, but there is a bit of a disconnect between them. Take .female as an example. Does it refer to a female human being or some kind of female animal? And .hand, is it talking about the hands of a clock (Annotation: hand means hands in English)? Or a hand playing cards? Using BEM we can get more description and a clearer structure, and we can know the relationship between elements just through the naming in our code. BEM is really powerful.

Let’s look at another example of .site-search named in the ‘conventional’ way:

<form class="site-search  full">
  <input type="text" class="field">
  <input type="Submit" value ="Search" class="button">
</form>
Copy after login

These CSS class names are really imprecise and don’t tell us enough information. While we can get the job done with them, they are really vague. Using BEM notation, it will look like this:

<form class="site-search  site-search--full">
  <input type="text" class="site-searchfield">
  <input type="Submit" value ="Search" class="site-searchbutton">
</form>
Copy after login

We can clearly see that there is a block called .site-search, and inside it is a block called .site -element of searchfield. And .site-search also has another form called .site-search--full.

Let’s give another example...

If you are familiar with OOCSS (Object-orientedCSS), then you must be familiar with media objects. Using BEM, the media object will look like this:

.media{}.mediaimg{}.mediaimg--rev{}.mediabody{}
Copy after login

From this CSS writing method, we already know that .mediaimg and .mediabody must be It is located inside .media, and .mediaimg--rev is another form of .mediaimg. We can get all the above information just through the name of CSS selector.

Another benefit of BEM is for the following situation:

<p class="media">
  <img src="logo.png" alt="Foo Corp logo" class="img-rev">
  <p class="body">
    <h3 class="alpha">Welcome to Foo Corp</h3>
    <p class="lede">Foo Corp is the best, seriously!</p>
  </p>
</p>
Copy after login

Just from the above code, we don’t understand how the two classes .media and .alpha interact with each other. Inter-related? Similarly, we have no way of knowing what the relationship is between .body and .lede, or between .img-rev
and .media? From this HTML (unless you know the media object very well) we don't know what this component is composed of and what other forms it has. If we rewrite this code in BEM way:

<p class="media">
  <img src="logo.png" alt="Foo Corp logo" class="mediaimg--rev">
  <p class="mediabody">
    <h3 class="alpha">Welcome to Foo Corp</h3>
    <p class="lede">Foo Corp is the best, seriously!</p>
  </p>
</p>
Copy after login

我们立马就能明白.media是一个块,.mediaimg--rev是一个加了修饰符的.mediaimg的变体,它是属于.media的元素。而.mediabody是一个尚未被改变过的也是属于.media的元素。所有以上这些信息都通过它们的class名称就能明白,由此看来BEM确实非常实用。

丑极了!

通常人们会认为BEM这种写法难看。我敢说,如果你仅仅是因为这种代码看上去不怎么好看而羞于使用它,那么你将错失最重要的东西。除非使用BEM让代码增加了不必要的维护困难,或者这么做确实让代码更难读了,那么你在使用它之前就要三思而行了。但是,如果只是“看起来有点怪”而事实上是一种有效的手段,那么我们在开发之前当然应该充分考虑它。

是,BEM看上去确实怪怪的,但是它的好处远远超过它外观上的那点瑕疵。

BEM可能看上去有点滑稽,而且有可能导致我们输入更长的文本(大部分编辑器都有自动补全功能,而且gzip压缩将会让我们消除对文件体积的担忧),但是它依旧强大。

用还是不用BEM?

我在我的所有项目中都使用了BEM记号法,因为它的有效性已经被它自己一次又一次地证明。我也极力地建议别人使用BEM,因为它让所有东西之间的联系变得更加紧密,让团队甚至是你个人都能够更加容易地维护代码。

然而,当你真正使用BEM的时候,重要的是,请记住你没必要真的在每个地方都用上它。比如:

.caps{ text-transform:uppercase; }
Copy after login

这条CSS不属于任何一个BEM范畴,它仅仅只是一条单独的样式。

另一个没有使用BEM的例子是:

.site-logo{}
Copy after login

这是一个logo,我们可以把它写成BEM格式,像下面这样:

.header{}.headerlogo{}
Copy after login

但我们没必要这么做。使用BEM的诀窍是,你要知道什么时候哪些东西是应该写成BEM格式的。因为某些东西确实是位于一个块的内部,但这并不意味它就是BEM中所说的元素。这个例子中,网站logo完全是恰巧在.header的内部,它也有可能在侧边栏或是页脚里面。一个元素的范围可能开始于任何上下文,因此你要确定只在你需要用到BEM的地方你才使用它。再看一个例子:

<p class="content">
  <h1 class="contentheadline">Lorem ipsum dolor...</h1>
</p>
Copy after login

在这个例子里,我们也许仅仅只需要另一个class,可以叫它.headline;它的样式取决于它是如何被层叠的,因为它在.content的内部;或者它只是恰巧在.content的内部。如果它是后者(即恰巧在.content的内部,而不总是在)我们就不需要使用BEM。

然而,一切都有可能潜在地用到BEM。我们再来看一下.site-logo的例子,想象一下我们想要给网站增加一点圣诞节的气氛,所以我们想有一个圣诞版的logo。于是我们有了下面的代码:

.site-logo{}.site-logo--xmas{}
Copy after login

我们可以通过使用--修饰符来快速地为我们的代码构建另一个版本。

BEM最难的部分之一是明确作用域是从哪开始和到哪结束的,以及什么时候使用(不使用)它。随着接触的多了,有了经验积累,你慢慢就会知道怎么用,这些问题也不再是问题。

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

在表单中button与input的区别

详谈css样式初始化 

js的自定义trim函数使用方法

The above is the detailed content of Detailed explanation of BEM syntax. 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)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

What are the syntax and structure characteristics of lambda expressions? What are the syntax and structure characteristics of lambda expressions? Apr 25, 2024 pm 01:12 PM

Lambda expression is an anonymous function without a name, and its syntax is: (parameter_list)->expression. They feature anonymity, diversity, currying, and closure. In practical applications, Lambda expressions can be used to define functions concisely, such as the summation function sum_lambda=lambdax,y:x+y, and apply the map() function to the list to perform the summation operation.

Detailed explanation of numpy version query method Detailed explanation of numpy version query method Jan 19, 2024 am 08:20 AM

Numpy is a Python scientific computing library that provides a wealth of array operation functions and tools. When upgrading the Numpy version, you need to query the current version to ensure compatibility. This article will introduce the method of Numpy version query in detail and provide specific code examples. Method 1: Use Python code to query the Numpy version. You can easily query the Numpy version using Python code. The following is the implementation method and sample code: importnumpyasnpprint(np

See all articles