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:
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:
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:
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 */ }
}
```
[
## 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.

The function of HTML is to define the structure and content of a web page, and its purpose is to provide a standardized way to display information. 1) HTML organizes various parts of the web page through tags and attributes, such as titles and paragraphs. 2) It supports the separation of content and performance and improves maintenance efficiency. 3) HTML is extensible, allowing custom tags to enhance SEO.

The future trends of HTML are semantics and web components, the future trends of CSS are CSS-in-JS and CSSHoudini, and the future trends of JavaScript are WebAssembly and Serverless. 1. HTML semantics improve accessibility and SEO effects, and Web components improve development efficiency, but attention should be paid to browser compatibility. 2. CSS-in-JS enhances style management flexibility but may increase file size. CSSHoudini allows direct operation of CSS rendering. 3.WebAssembly optimizes browser application performance but has a steep learning curve, and Serverless simplifies development but requires optimization of cold start problems.

The roles of HTML, CSS and JavaScript in web development are: 1. HTML defines the web page structure, 2. CSS controls the web page style, and 3. JavaScript adds dynamic behavior. Together, they build the framework, aesthetics and interactivity of modern websites.

The future of HTML is full of infinite possibilities. 1) New features and standards will include more semantic tags and the popularity of WebComponents. 2) The web design trend will continue to develop towards responsive and accessible design. 3) Performance optimization will improve the user experience through responsive image loading and lazy loading technologies.

The roles of HTML, CSS and JavaScript in web development are: HTML is responsible for content structure, CSS is responsible for style, and JavaScript is responsible for dynamic behavior. 1. HTML defines the web page structure and content through tags to ensure semantics. 2. CSS controls the web page style through selectors and attributes to make it beautiful and easy to read. 3. JavaScript controls web page behavior through scripts to achieve dynamic and interactive functions.

HTMLisnotaprogramminglanguage;itisamarkuplanguage.1)HTMLstructuresandformatswebcontentusingtags.2)ItworkswithCSSforstylingandJavaScriptforinteractivity,enhancingwebdevelopment.

HTML is the cornerstone of building web page structure. 1. HTML defines the content structure and semantics, and uses, etc. tags. 2. Provide semantic markers, such as, etc., to improve SEO effect. 3. To realize user interaction through tags, pay attention to form verification. 4. Use advanced elements such as, combined with JavaScript to achieve dynamic effects. 5. Common errors include unclosed labels and unquoted attribute values, and verification tools are required. 6. Optimization strategies include reducing HTTP requests, compressing HTML, using semantic tags, etc.

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

Dreamweaver Mac version
Visual web development tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software