BEM

 BEM이란 class 이름을 block, element, modifier로 나눠서 작성하는 것이다.

 

사용법

 block__element--modifier

 위에서 block은 전체적인 container가 된다고 할 수 있는 card이다. 그래서 단순하게 class 이름을 .card라고 해주면 된다.

 

 이 card 안에 들어가 있는 content들, 즉 image, description, button이 elements이다.

 

 이 때 button 사이에 success와 back이라는 2가지 버전(modifier)이 존재한다면 --로 덧붙여주면 된다. 만약 이 button이 해당 card에서 뿐만 아니라 다른 곳에서도 범용적으로 사용된다면 .card__button--success, .card__button--back이라고 하기 보다는 그저 .button--success, .button--back이라고 해주는 것이 재사용성 측면에서 효율적이다.

 

 

 

 이미지 출처 : https://blog.yanis.work/block-element-modifier-bem-css-methodology-df9db9771c6f

'프로그래밍 > CSS' 카테고리의 다른 글

Custom Properties  (0) 2022.03.07

 Custom Properties

.first-list {
  background-color: thistle;
  color: whitesmoke;
  margin-left: 8px;
  --font-size: 32px;
}

.second-list {
  background-color: thistle;
  color: whitesmoke;
  margin-left: 16px;
  font-size: var(--font-size);
}

 위와 같이 계속해서 하드코딩하는 것은 효율적이지 못하다. 코드 양이 방대해질 경우 일일이 수정하기 어렵기 때문이다. 다행히 CSS에서도 이러한 것을 방지하고 재사용성을 높이기 위해 변수를 사용할 수 있다.

 

 기본 사용법

.first-list {
  background-color: thistle;
  color: whitesmoke;
  margin-left: 8px;
  --font-size: 32px;
  /* font-size: var(--font-size); */
}

.first-list li {
  font-size: var(--font-size);
}

.second-list {
  background-color: thistle;
  color: whitesmoke;
  margin-left: 16px;
  font-size: var(--font-size);
}

 변수로 지정되길 원하는 속성에다가 --을 앞에 붙여주면 된다. --font-size과 같이 하면 된다. 그리고 해당 변수를 사용할 때는 var로 가둬줘야 한다. var(--font-size)처럼 말이다. 그리고 CSS 변수는 본인과 자식 요소에게 적용이 된다. 따라서 .second-list에서의 --font-size는 작용하지 않는다.

 

:root {
  --font-size: 32px;
  --background-color: thistle;
  --text-color: whitesmoke;
  /* --base-space: 8px; */
}

.first-list {
  background-color: var(--background-color);
  color: var(--text-color);
  margin-left: var(--base-space ,8px);
  font-size: var(--font-size);
}

.second-list {
  background-color: var(--background-color);
  color: var(--text-color);
  margin-left: calc(var(--base-space) * 2);
  font-size: var(--font-size);
}

@media screen and (max-width: 768px) {
  :root {
    --font-size: 16px;
    --background-color: blue;
    --text-color: white;
    --base-space: 4px;
  }
}

 이렇게 어느 곳에는 적용 되고, 어느 곳에는 적용이 안되는 것을 방지하기 위해 가장 최상위의 요소(root)에다가 CSS 변수를 선언한다.

 

 이제, 변경하고 싶은 style이 있다면 :root에서 수치만 변경하면 된다. 그리고 변수명은 어디에 사용되는 변수인지 직관적으로 알 수 있게 지어줘야 한다.

 

 미디어 쿼리에서도 응용이 가능하다. 화면의 크기가 768px보다 작아지게 되면 해당 CSS 변수가 적용되게 된다.

 

 기본값

.first-list {
  margin-left: var(--base-space, 8px);
}

 만약 해당 변수를 찾을 수 없다면 두 번째 인자로 기본값을 줘서 적용해줄 수도 있다.

 

 

 

 Custom Properties MDN : https://developer.mozilla.org/ko/docs/Web/CSS/Using_CSS_custom_properties

'프로그래밍 > CSS' 카테고리의 다른 글

BEM  (0) 2022.03.07

+ Recent posts