BEM ( Block Element Modifier )
.header__nav--sta
위와 같은 스타일의 클래스작명규칙( naming convention )을 BEM이라 한다.
각 요소의 연관성을 분명하게 볼 수 있는 것이 장점이다.
아래글은 csswizardry.com의 글을 가져온 것입니다.
BEM Naming Convention
1 2 3 | .block{} .block__element{} .block--modifier{} | cs |
.block
은 높은단계의 구성요소를 말한다.
.block__element
는 .block
의 자식을 나타낸다.
.block--modifier
는 .block
의 다른 상태나 버전을 나타낸다.
좀 더 쉽게 예를 들어보자면 아래와 같다.
1 2 3 4 5 | .person{} .person__hand{} .person--female{} .person--female__hand{} .person__hand--left{} | cs |
최고 단계는 '사람'이고 '사람'을 구성하는 요소는 '손'이 있다.
또한 '사람'은 '여성'이라는 다른버전(?)이 있다. 이 다른버전의 사람또한 '손'을 구성요소로 가지고 있다.
위의 코드를 보니 클래스간의 연관성이 확실히 눈에 잘 들어온다.
이걸 그냥 일반적인 css로 써본다면 아래와 같다.
1 2 3 4 5 | .person{} .hand{} .female{} .female__hand{} .left-hand{} | cs |
각각의 클래스가 의미는 있지만 클래스간의 연관성은 찾아보기 힘들다고 할 수 있다.
BEM의 강점을 느낄 수 있는가?
1 2 3 4 | <form class="site-search full"> <input type="text" class="field"> <input type="Submit" value ="Search" class="button"> </form> | cs |
위의 클래스 설정만으로도 우리는 모든 작업을 할 수 있다.
허나 각각의 요소들이 가진 관계에 비해 클래스명은 너무 개별적이다.
이것을 BEM표기법으로 바꿔보도록 하자.
1 2 3 4 | <form class="site-search site-search--full"> <input type="text" class="site-search__field"> <input type="Submit" value ="Search" class="site-search__button"> </form> | cs |
.site-search
를 보고 우리는 '아 이것이 가장 상위블록이구나' 라는걸 금방 알 수 있다.
그 안에는 .site-search__field
와 .site-search__button
이라는 자식 요소가 있고 .site-search--full
이라부르는 상위블록의 변형이 있다는 걸 알수도 있다.