Programming/Styles

[CSS] BEM, 중복 component 설정

Jiwoo 2022. 3. 26. 15:29

🤔 BEM이란?

Block / Element / Modifier

세 가지로 구성된 class이름을 짓는 방법

📌 미사용시

<form id="login-form">
      <input type="text" placeholder="Email or phone number" />
      <input type="password" placeholder="Password" />
      <input type="submit" value="Log in" />
      <a href="#">Find Kakao Account of Password</a>
    </form>
#login-form input:not([type="submit"]) {
  border-bottom: 1px solid rgba(0, 0, 0, 0.2);
  transition: border-color 0.3s ease-in-out;
}

#login-form input[type="submit"] {
  background-color: var(--yellow);
  cursor: pointer;
  padding: 20px 0;
  border-radius: 5px;
}

📌사용시

<header class="welcome-header">
      <h1 class="welcome-header__title">welcome to kakaoTalk</h1>
      <p class="welcome-header__text">
        If you have a Kakao Account, log in with your email or phone number.
      </p>
    </header>
.welcome-header__title {
  font-size: 25px;
  margin-bottom: 40px;
}

.welcome-header__text {
  width: 60%;
  opacity: 0.7;
}

.welcome-header {
  margin: 90px 0;
  text-align: center;
  display: flex;
  flex-direction: column;
  align-items: center;
}

누가 봐도 BEM 방식이 보기 편하다!

📌 중복 component에 특수 속성 적용

  • 기본 component 생성 (user-component__avatar)

    <img
      class="user-component__avatar"
      src="/img.jpg"
      />
  • 속성이 다른 component 만들기

    • modifier 붙인 class 생성 (user-component__avatar—xl)
    • 원 class 옆에 작성
    <img
       class="user-component__avatar user-component__avatar--xl"
       src="/img.jpg"
      />
  • (css) 기본 속성보다 밑에 특수 속성 작성

    /*기본 속성*/
    .user-component__avatar {
      width: 70px;
      height: 70px;
      border-radius: 27px;
      margin-right: 20px;
    }
    
    /*특수 속성*/
    .user-component__avatar--xl {
      width: 80px;
      height: 80px;
    }

이렇게 하면 특수 속성이 최종적으로 적용되고 보기도 좋다!