코드는 가독성이 중요하다. Show 하지만 코드양이 많아지면 그만큼 클래스명도 다양해지고 구조 또한 복잡해진다. 그래서 클래스 명의 명확성과 일관성, 의미론을 유지할수 있는 CSS 표준에는 BEM 표기법이 있다. BEM 은 Block Element Modifier 의 약자이다. 클래스 이름 안에 언더바 두개씩 있고, 마이너스 표시가 그 뒤에 두개씩 있는 경우를 접해본적이 있다면, 그게 BEM 을 활용한 클래스의 표기이다. 예시) main__item--blue 하지만 간혹 보면 BEM 표기법을 아이디에 사용하는 경우도 종종 있는데, 이는 잘못된 방법으로, 클래스에만 사용하여야 한다. 하단의 간단한 예제를 통해 BEM 의 의미를 이해하도록 하자 샘플 예제Html
설명 Block : <section class="main"></main> Element : <div class="main__item"></div> Modifier : <div class="main__item--blue"></div> 전체를 감싸고있는 회색의 블록의 클래스 이름은 main으로 하였다. 감싸져있는 내부의 엘리먼트들은 main__item 그안에서 구분하기 위한 엘리먼트는 main__item--blue The following is a collaborative post by guest Joe Richardson, Robin Rendle, and a bunch of the CSS-Tricks staff. Joe wanted to do a post about BEM, which we loved, and just about everybody around here had thoughts and opinions about BEM, so we figured we’d all get together on it and do it together. The Block, Element, Modifier methodology (commonly referred to as BEM) is a popular naming convention for classes in HTML and CSS. Developed by the team at Yandex, its goal is to help developers better understand the relationship between the HTML and CSS in a given project. Here’s an example of what a CSS developer writing in the BEM style might write:
In this CSS methodology a
block is a top-level abstraction of a new component, for example a button: The markup might then look like this:
If another developer wrote this markup, and we weren’t familiar with the CSS, we should still have a good idea of which classes are responsible for what and how they depend on one another. Developers can then build their own components and modify the existing block to their heart’s content. Without writing much CSS, developers are potentially capable of creating many different combinations of buttons simply by changing a class in the markup: See the Pen BEM example by CSS-Tricks (@css-tricks) on CodePen. At first this syntax might seem slower than simply making a new class for each type of button, but this is not the case for several reasons we’ll cover. Why should we consider BEM?
Harry Roberts identified another key benefit of using a syntax like BEM when he writes about improving developer confidence:
Likewise, Philip Walton argues that this problem can be fixed if enough developers stick to the principles of BEM:
So if developers can work on a project more confidently, then they’re sure to make smarter decisions about how these visual components should be used. This methodology might not be a perfect cure for all these ailments, but it certainly gives developers a standard on which to write better, more maintainable code in the future. Another smart part of BEM is that everything is a class and nothing is nested. That makes CSS specificity very flat and low, which is a good idea. It means you won’t end up fighting with yourself over specificity. Let’s take a look at some of the problems with BEM… Problems with BEM CSSOf course nobody will twist your arm if you break from BEM rules. You could still write a CSS selector like this:
That looks like it has parts of BEM going on, but it’s not BEM. It has nested selectors, and the modifier doesn’t even accurately describe what’s going on. If we did this, we’d be screwing up the specificity flatness that is so helpful with BEM. A block (such as
What’s probably going on here is that an element in a completely unrelated block has
the code a developer needed, but the child elements don’t require a
More examples of BEM in actionAccordion demoSee the Pen BEM Accordion by CSS-Tricks (@css-tricks) on CodePen. In this example there is one block, two elements and one modifier. Here we’ve can created an Navigation demoSee the Pen BEM Menu by CSS-Tricks (@css-tricks) on CodePen. This navigation demo has 1 block, 6 elements and 1 modifier. It’s even perfectly OK to create blocks without modifiers at all. At some point in the future a developer can always bolt on (or bind to) new modifiers so long as the block remains consistent. Dislikes of BEMPerhaps you don’t like the double-underscores or double-dashes thing. Fine, use something else that is unique that you will consistently enforce. Here’s another sentiment:
Those last three selectors all have different specificity levels. They either require parents or not. Without any rules in place, they don’t say as much as the ones on top. Is it possible that this tiny, isolated example feels perfectly fine to you and never ends up biting you in the butt? Perhaps. But the more CSS you have in a project, the more little things like this add up, the more specificity and complexity battles you go through.
Not to pick on Samuel here, but his sentiments are shared by a lot of people so it makes for a good example. They see BEM, and they just outright reject it. If you want to dislike BEM, that’s absolutely fine, but I think it would be hard to argue that having a set of rules that aid in understanding and assist in keeping CSS maintainable is a bad idea. In the SMACSS methodology, you’re likely to find a CSS classname with three letters. Modifiers then follow the module name with a hyphen:
That’s just a different naming approach to the same kind of problem. It’s pretty similar, but you’re just being more specific about dependencies and keeping specificity flatter. In OOCSS, blocks are similarly generic.
So you would use multiple classes in the HTML for variations. The inside part isn’t named like it has a dependency, so it is less clear but
potentially more reusable. BEM would do These are just variations on methodology. Remember that nobody is twisting your arm here, these are self-imposed rules where the value comes from following them. Sass and BEMFor those of you writing Sass and enjoy nesting as a way of scoping styles, you can still author in a nested format, but get CSS that isn’t nested, with
Gets you:
And you can get as abstract as you want! Check out Danield Guillan’s BEM Constructor or Anders Schmidt Hansen’s Expressive BEM. SummaryTo wrap things up I think it’s fair to say that even though BEM won’t solve all our problems it is extraordinarily useful for constructing scalable and maintainable interfaces where everyone on the team should have a clear idea of how things can be improved. This is because a great deal of front end development is not just about the nice tricks that solve one little problem in the short term; we need agreements, promises and binding social contracts between developers so that our codebase can adapt over time. Generally I like to think of BEM as an answer to Nicolas Gallagher’s question:
Further reading
|