search
HomeWeb Front-endHTML TutorialTranslation: Nesting Your BEM?

Original link: http://csswizardry.com/2016/11/nesting-your-bem/

Before I start this article, I have to say that this is not a suggestion or a new “practice guide”. This is just some of my own fantasies.

I am an advocate and supporter of [BEM](http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/). And it has been for many years. It's kind of fun to look forward to. Of course, it provides me with a lot of things:

* **Soft Encapsulation** This helps reduce naming conflicts.
* **Customized CSS** This helps me understand how DOM nodes relate to each other.
* **Target Selection** This helps reduce conflicts between subtrees and avoid capturing too many nodes.
* **Speciality of Management Style** This is a big highlight.
* **Strict Implementation Rules** This prevents me from using classes outside of the given context.

Except for the last point which is only half true...

BEM tells us that a class, for example: `.widget__title`, can only be used within `.widget`. But this is only a stipulation of the agreement. A developer might put `.widget_title` inside `.model` and still have it work. This is because:

* They haven’t seen BEM before, or don’t know how to implement it
* They are lazy and find out that - even though they shouldn’t, they can reuse the .widget_title style inside `.modal`, Then you can complete the work 5 minutes earlier

They can do it and it works for them: things still display correctly. This does not lead to additional errors, as BEM is only a regulation, and regulations require unanimous agreement.

To circumvent this, we can write CSS like this:

```
.widget { }

.widget .widget__title { }
```

Now developers cannot use `.widget_title` inside `.modal` because we told our CSS that `wideget_title` will only work if we put it inside `.widget`. Now we start enforcing these things and it will prevent abuse.

There is another problem here: nesting

## Nesting in CSS


For a long time I [actively argued](http://cssguidelin.es/#specificity) that nesting in CSS was a bad thing because:

* Added features (these should always be managed);
* Introduced dependency on storage location (a sign of an inflexible system);
* Decreased portability (meaning we can't move it around at will) ;
* Increased fragility (nested means increased chance of wrong selectors).

In summary, [Keep your CSS selectors short](http://csswizardry.com/2012/05/keep-your-css-selectors-short/).

But in the case of using nested BEM, we see that nesting brings us real benefits. But how do we deal with these flaws?

## Specificity

Note that it is generally important to always maintain low specificity. That's absolutely true, and it's great advice. However, there is a little difference here from the ones we are familiar with. When people say that specificity should be handled in all cases, what they really mean is that we should maintain consistency and have little difference between selectors.

Theoretically (but, dear, please don't try this), the only selector for an item is the ID selector, which would manage specificity well: specificity is generally high, but at least everything matches and equal.

When we talk about how to deal with the problem of consistency: we are referring to its [specificity map](http://csswizardry.com/2014/10/the-specificity- graph/) as smooth as possible.

If we look at the following series of CSS components:

```
.nav-primary { }

.nav-primary__item { }

.nav-primary__link { }

.masthead { }

.masthead__media { }

.masthead__text { }

.masthead__title { }

.sub-content { }

.sub-content__title { }

.sub-content__title--featured { }

.sub-content__img { }
```

...We found that each of their classes has exactly the same specificity. Here’s a nice flat specificity plot:

![Graph showing low and flat specificity](http://p0.qhimg.com/t01298e8f9265d223bb.png)

[View large image](http://csswizardry.com/wp-content/uploads/2016/11/graph-specificity-01.png)
> ;

Once we nest these classes like this:

```
.nav-primary { }

.nav-primary .nav-primary__item { }

.nav-primary .nav-primary__link { }

.masthead { }

.masthead .masthead__media { }

.masthead .masthead__text { }

.masthead .masthead__title { }

.sub-content { }

.sub-content .sub-content__title { }

.sub-content .sub-content__title--featured { }

.sub-content .sub-content__img { }
```

…The specificity plot we see will look like this:

![Graph showing changes in specificity](http://p0.qhimg.com/t01afba20a956d400fc.png)

[View large image](http://csswizardry.com/wp-content/uploads/2016/11/graph-specificity-02.png)
> ;

Oh my gosh! Spikes! Spikes are exactly what we want to avoid, as they represent fluctuations in specificity between selectors that are very close together in the project.

Here we are visualizing the specificity downside to nesting. Can we avoid it? how to do?

## Link to the first class

If we want to link the first class (the Block) to itself, like this:

```
.nav-primary.nav-primary { }

.nav-primary .nav-primary__item { }

.nav-primary .nav-primary__link { }

.masthead.masthead { }

.masthead .masthead__media { }

.masthead .masthead__text { }

.masthead .masthead__title { }

.sub-content.sub-content { }

.sub-content .sub-content__title { }

.sub-content .sub-content__title--featured { }

.sub-content .sub-content__img { }
```

…we can make it specifically match all nested elements without side effects:

* We don’t need to know the location of this Block in the DOM, so we don’t increase its specificity based on some possible changing positions
* We are not connected to a different or specific element or class. This means that the Block class is still very lightweight.

This increase in specificity is entirely dependent on itself, and now we see a specificity map like this:

![Graph showing higher but still flat specificity](http://p0.qhimg.com/t01cecef3a98ac52bbf.png)

[View large image](http://csswizardry.com/wp-content/uploads/2016/11/graph-specificity-03.png)
> ;

Higher than the first picture, but still very smooth. Even though our specificity is two levels high, it's still well managed: our selector component has no special weight.

## Simplified with Sass

To make nesting and linking easier, we can use preprocessing, in this case Sass:

We should all be familiar with how to nest regular selectors in Sass:

```
.nav-primary {

.nav-primary__item { }

.nav-primary__link { }

}
```

This brings us, just as we expected:

```
.nav-primary { }

.nav-primary .nav-primary__item { }

.nav-primary .nav-primary__link { }
```

But how do we quickly and effectively link the first class to itself? Like this:

```
.nav-primary {

{&} { }

.nav-primary__item { }

.nav-primary__link { }

}
```

By using `{&}`, we can link the current class to itself. This means that all of our Block's styles (in this case, `.nav-primary`) are here:

```
.nav-primary {

{&} { /* Block styles */ }

}
```

[Look at a small example about Sassmeister](http://www.sassmeister.com/gist/a14e5b242ee6b20932dd44df0a3d215c)

## Actual results

Now, we are in a situation where we are actually forcing the use of selectors and actively preventing them from taking effect - if we actively move them out of the correct part of the DOM. This helps us work in environments where other developers don't know how BEM works, or are people who tend to mess around until everything looks right.

We also have a specificity that manages all classes (albeit increased)

### Defects

We are adding some specificity, which is generally what we should always strive to avoid.

## Use Case

If you want to try to extend this technology, it is necessary to identify some key use cases before starting. The first thing that popped into my mind were grid systems. Time and time again, I see developers trying to use the `.grid__item` class in addition to the `.grid` parent class. So, if I were going to start using this technique, I would start here:

```
.grid.grid { }

.grid .grid__item { }
```

## To use or not to use?

I'm not sure, as I said at the beginning, this is not a technology that I highly recommend and am committed to implementing. I just wanted to bring it up as a reference, especially for developers who find themselves in an environment where other developers are abusing CSS so easily.

However, what I want to say is: if you have nested your BEM, please go back and flatten your specificity map by linking your first class.

Statement
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
The Future of HTML: Evolution and TrendsThe Future of HTML: Evolution and TrendsMay 13, 2025 am 12:01 AM

The future of HTML will develop in a more semantic, functional and modular direction. 1) Semanticization will make the tag describe the content more clearly, improving SEO and barrier-free access. 2) Functionalization will introduce new elements and attributes to meet user needs. 3) Modularity will support component development and improve code reusability.

Why are HTML attributes important for web development?Why are HTML attributes important for web development?May 12, 2025 am 12:01 AM

HTMLattributesarecrucialinwebdevelopmentforcontrollingbehavior,appearance,andfunctionality.Theyenhanceinteractivity,accessibility,andSEO.Forexample,thesrcattributeintagsimpactsSEO,whileonclickintagsaddsinteractivity.Touseattributeseffectively:1)Usese

What is the purpose of the alt attribute? Why is it important?What is the purpose of the alt attribute? Why is it important?May 11, 2025 am 12:01 AM

The alt attribute is an important part of the tag in HTML and is used to provide alternative text for images. 1. When the image cannot be loaded, the text in the alt attribute will be displayed to improve the user experience. 2. Screen readers use the alt attribute to help visually impaired users understand the content of the picture. 3. Search engines index text in the alt attribute to improve the SEO ranking of web pages.

HTML, CSS, and JavaScript: Examples and Practical ApplicationsHTML, CSS, and JavaScript: Examples and Practical ApplicationsMay 09, 2025 am 12:01 AM

The roles of HTML, CSS and JavaScript in web development are: 1. HTML is used to build web page structure; 2. CSS is used to beautify the appearance of web pages; 3. JavaScript is used to achieve dynamic interaction. Through tags, styles and scripts, these three together build the core functions of modern web pages.

How do you set the lang attribute on the  tag? Why is this important?How do you set the lang attribute on the tag? Why is this important?May 08, 2025 am 12:03 AM

Setting the lang attributes of a tag is a key step in optimizing web accessibility and SEO. 1) Set the lang attribute in the tag, such as. 2) In multilingual content, set lang attributes for different language parts, such as. 3) Use language codes that comply with ISO639-1 standards, such as "en", "fr", "zh", etc. Correctly setting the lang attribute can improve the accessibility of web pages and search engine rankings.

What is the purpose of HTML attributes?What is the purpose of HTML attributes?May 07, 2025 am 12:01 AM

HTMLattributesareessentialforenhancingwebelements'functionalityandappearance.Theyaddinformationtodefinebehavior,appearance,andinteraction,makingwebsitesinteractive,responsive,andvisuallyappealing.Attributeslikesrc,href,class,type,anddisabledtransform

How do you create a list in HTML?How do you create a list in HTML?May 06, 2025 am 12:01 AM

TocreatealistinHTML,useforunorderedlistsandfororderedlists:1)Forunorderedlists,wrapitemsinanduseforeachitem,renderingasabulletedlist.2)Fororderedlists,useandfornumberedlists,customizablewiththetypeattributefordifferentnumberingstyles.

HTML in Action: Examples of Website StructureHTML in Action: Examples of Website StructureMay 05, 2025 am 12:03 AM

HTML is used to build websites with clear structure. 1) Use tags such as, and define the website structure. 2) Examples show the structure of blogs and e-commerce websites. 3) Avoid common mistakes such as incorrect label nesting. 4) Optimize performance by reducing HTTP requests and using semantic tags.

See all articles

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 Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)