[CSS] :not()

김민재·2025년 9월 7일

CSS property

목록 보기
2/4

리액트 프로젝트 진행 중에 다음과 같이 어떤 요소가 특정 클래스명을 가지고 있지 않은 경우에만 css 속성을 적용해야 하는 상황이 있었다.

  return (
    <fieldset
      className={`${styles["filter-field"]} ${
        isSelected ? styles["filter-field--active"] : ""
      } ${
        isFilterActive && !isSelected ? styles["filter-field--inactive"] : ""
      }`}

이 경우 다음과 같이 가상 클래스 :not(...)을 활용하면 특정 클래스가 아닌 경우에 따로 css 속성을 지정할 수 있다.

.filter-field {
  position: relative;
  border-right: 1px solid #e5e7eb;
  cursor: pointer;

  &:not(.filter-field--active):not(.filter-field--inactive) {
    &:hover {
      background: #ebebeb;
    }
  }

scss에서 &는 현재 선택자를 참조하는 특별한 기호이므로, 다음과 같은 css 코드와 의미가 동일하다.

.filter-field:not(.filter-field--active):not(.filter-field--inactive):hover {
  background: #ebebeb;
}

:not()의 인자로 가상 클래스를 받아서 다음과 같은 활용도 가능하다.

ul li:not(:last-child) {
  margin-bottom: 8px;
}

위 코드는 마지막 li 요소를 제외하고 모든 li에 margin을 적용하는 코드이다.
흔히 리스트 항목 간격 조절에 사용한다.


input:not(:checked) {
  background: #f0f0f0;
}

체크되지 않은 input만 선택한다.



요약

  • SCSS의 &현재 선택자를 참조하는 특별한 기호이다.
  • 가상 클래스 not()의 인자로는 어떤 셀렉터든 올 수 있으며, 다양한 활용이 가능하다.
profile
넓이보다 깊이있게

0개의 댓글