css의 &

김내현·2024년 11월 26일

개인공부

목록 보기
30/51

&

CSS에서 앰퍼샌드 기호(&)는 자체적으로 부모 선택자를 나타내지 않는다. 그러나 SASS(또는 SCSS)와 같은 CSS 전처리기에서는 앰퍼샌드 기호를 사용하여 부모 선택자를 참조할 수 있다. 이는 중첩된 규칙 내에서 부모 선택자를 나타내는 데 사용된다.

SASS에서의 앰퍼샌드(&) 사용

  • 부모 선택자 참조: SASS에서 & 기호는 중첩된 규칙 내에서 부모 선택자를 참조하는 데 사용됩니다. 예를 들어, 다음과 같은 코드가 있다면:

    .button {
      &:hover {
        color: blue;
      }
    }

    이는 컴파일되어 다음과 같은 CSS로 변환된다:

    .button:hover {
      color: blue;
    }
  • 선택자 수정: & 기호는 부모 선택자에 접미사를 추가하여 새로운 선택자를 생성하는 데도 사용된다. 예를 들어:

    .container {
      &-header {
        font-size: 20px;
      }
    }

    이 코드는 다음과 같이 컴파일된다:

    .container-header {
      font-size: 20px;
    }

따라서, CSS 자체에서는 & 기호가 사용되지 않지만, SASS와 같은 전처리기에서는 부모 선택자를 참조하거나 수정하는 데 유용하게 사용된다[1][2][3].

&

CSS-in-JS 라이브러리에서도 앰퍼샌드(&) 기호는 SASS와 유사하게 부모 선택자를 참조하는 데 사용된다. 이러한 라이브러리들은 JavaScript 환경에서 CSS 스타일을 작성할 수 있게 해주며, 스타일을 컴포넌트 단위로 관리할 수 있도록 돕는다.

CSS-in-JS에서 앰퍼샌드(&) 사용

  • 부모 선택자 참조: CSS-in-JS 라이브러리에서는 앰퍼샌드를 사용하여 현재 스타일이 적용된 컴포넌트를 참조할 수 있다. 이는 중첩된 스타일 규칙을 작성할 때 특히 유용하다.
  • 의사 클래스 및 의사 요소: & 기호를 사용하여 의사 클래스(e.g., &:hover)나 의사 요소(e.g., &::before)에 대한 스타일을 정의할 수 있다.

예시

예를 들어, Styled Components나 Emotion과 같은 라이브러리에서는 다음과 같이 사용할 수 있다:

const Button = styled.button`
  color: black;
  
  &:hover {
    color: blue;
  }
`;

이 코드는 버튼 컴포넌트가 마우스를 올렸을 때 텍스트 색상이 파란색으로 변경되도록 한다. 이는 SASS의 사용 방식과 매우 유사하다.

Citations:
[1] https://www.studytonight.com/sass/sass-parent-selector-using-ampersand
[2] https://blog.teamtreehouse.com/sass-tip-double-ampersand-selector
[3] https://www.geeksforgeeks.org/how-to-combine-parent-using-ampersand-with-type-selectors-in-sass/
[4] https://teamtreehouse.com/library/sass-basics-2/use-the-ampersand-to-reference-parent-selectors
[5] https://css-tricks.com/the-sass-ampersand/
[6] https://stackoverflow.com/questions/26519561/sass-referencing-parent-selectors-using-the-ampersand-character-within-nested-se/33176587
[7] https://sparkbox.com/foundry/how_to_use_ampersands_to_simplifiy_your_sass
[8] https://sass-lang.com/documentation/style-rules/parent-selector/
[9] https://www.hangulogame.com
[10] https://help.hancom.com/hoffice/webhelp/9.0/ko_kr/hwp/edit/to_hangul.htm
[11] https://haneng.kr
[12] https://haneng.kr/shop/list.php?ca_id=20
[13] https://jos39.tistory.com/185
[14] https://sass-guidelin.es/ko/
[15] https://inpa.tistory.com/entry/SCSS-%F0%9F%92%8E-SassSCSS-%EB%9E%80-%EC%84%A4%EC%B9%98-%EB%B0%8F-%EC%BB%B4%ED%8C%8C%EC%9D%BC
[16] https://persistent-weed-dev.tistory.com/entry/SASS-SCSS%EC%97%90-%EB%8C%80%ED%95%B4%EC%84%9C-%EC%95%8C%EC%95%84%EB%B3%B4%EC%9E%90

0개의 댓글