본문 바로가기

달밤에 코딩하기/HTML CSS Tip!

CSS 이름 작명 규칙 (BEM)

개발자에게는 CSS의 이름을 작성할 때 일정한 규칙이 있으며 이를 BEM 방법론이라고 한다. 

 

BEM이란?

Block-Element-Modifier의 약자로 CSS 클래스 이름에 대한 작명 규칙 표준이며 Sparkbox에서 널리 사용된다. 

BEM의 장점

BEM 규칙을 통해 아래 장점을 가질 수 있다.

  1. 목적과 기능 전달
  2. 구성 요소 구조 전달
  3. 스타일 선택자에 대한 낮은 수준의 일관성을 설정

작성 방법

구성 요소

BEM 클래스는 3개 부분으로 구성되며, 순서와 예시는 아래와 같다.

  1. 블록 : 상위 요소
  2. 요소 : 자식 요소
  3. 수정자 : 변형 요소
<div class="block__element--modifier">
</div

블록 사용

단순 구성 요소는 블록 요소만 사용할 수 있다.

HTML

<div class="btn">button</div>

CSS

.btn{
    height: 34px;
    background:  #eee;
    border: 1px solid #d5d5d5;
    border-radius: 4px;
    display: flex;
    align-items: center;
    padding: 0 12px;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.5;
    cursor: pointer;
    box-sizing: border-box;
    position: relative;
    color: #333;
}
/*버튼에 마우스 오버 시 스타일 정의*/
.btn:hover::before{
    content: "";
    position: absolute;
    top : 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.07);
}

블록+수정자 사용

블록 요소(class='btn')를 기준으로 하여 수정자(class="btn--primary")를 정의한다. 이때, 수정자 클래스는 블록 클래스를 보강하는 것이기 때문에 단독으로 사용하면 안 된다.

HTML

<div class="btn btn--primary">button</div>

CSS

/*기본 버튼에 대한 정의*/
.btn{
    height: 34px;
    background:  #eee;
    border: 1px solid #d5d5d5;
    border-radius: 4px;
    display: flex;
    align-items: center;
    padding: 0 12px;
    font-size: 14px;
    font-weight: 500;
    line-height: 1.5;
    cursor: pointer;
    box-sizing: border-box;
    position: relative;
    color: #333;
}
/*버튼에 마우스 오버 시 스타일 정의*/
.btn:hover::before{
    content: "";
    position: absolute;
    top : 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.07);
}
/*버튼의 프라이머리 수정자 스타일 정의*/
.btn.btn--primary{
    border:1px solid #cf7118;
    color : #fff;
    background: #fa9435 ;
}

블록+요소 사용

특이성을 낮추고 일관성을 유지하기 위해, 부모 요소와 자식 요소를 묶어 이름으로 지정한다. 부모 자식을 1개씩 묶어주어야 하기 때문에, body__main__title과 같은 형식으로 사용하면 안 된다.

HTML

<body>
    <section class="main">
        <div class="main__title">title</div>
        <div class="main__description">description</div>
    </section>
    <section class="sub">
        <div class="sub__title">title</div>
        <div class="sub__description">description</div>
    </section>
</body>

 

 


 

 

그 밖의 자세한 사항은 아래 사이트에서 확인할 수 있다.

 

#참고 사이트

https://sparkbox.com/foundry/bem_by_example

 

BEM by Example: Best Practices for BEM CSS Naming

BEM is a popular CSS naming convention. While the fundamentals of BEM are simple and straightforward, mistakes are common. These BEM examples will help you apply this useful naming convention and avoid some of the pitfalls many face when using BEM naming c

sparkbox.com