sass는 쉽게 말해 css를 확장해주는 라이브러리이다.
설치
$ cd styling-with-sass
$ yarn add node-sass
//class names 설치
$ yarn add classnames
.scss 파일
//변수선언
$blue: #228be6;
.Button {
display: inline-flex;
color: white;
font-weight: bold;
outline: none;
border-radius: 4px;
border: none;
cursor: pointer;
height: 2.25rem;
padding-left: 1rem;
padding-right: 1rem;
font-size: 1rem;
background: $blue; // 주석 사용
&:hover {
background: lighten($blue, 10%); // 색상 10% 밝게
}
&:active {
background: darken($blue, 10%); // 색상 10% 어둡게
}
//&으로 세부 옵션을 설정할 수 있다.
//Button.small 과 동일하다.
&.small {
height: 1.75rem;
font-size: 0.875rem;
padding-left: 1rem;
padding-right: 1rem;
}
&.large {
height: 3rem;
padding-left: 1rem;
padding-right: 1rem;
font-size: 1.25rem;
}
//컴포넌트가 붙어있는 경우
& + & {
margin-left: 1rem;
}
}
$로 변수를 선언할 수 있고, lighten, darken과 같은 함수를 사용할 수 있다.
& 문법으로 상태나 세부 디자인을 한 괄호안에 묶을 수 있다.
또, 여러 개의 컴포넌트가 붙어있는 경우를 & + &로 표현할 수 있다.
@Mixin
@mixin button-color($color) {
background: $color;
&:hover {
background: lighten($color, 10%);
}
&:active {
background: darken($color, 10%);
}
}
.Button{
&.blue {
@include button-color($blue);
}
&.gray {
@include button-color($gray);
}
&.pink {
@include button-color($pink);
}
}
@mixin을 사용해서 중복되는 코드를 줄이고 parameter를 받을 수 있다. @include로 @mixin 스타일을 다른 스타일에 포함 시킬 수 있다.
@for
@mixin generate-grid-areas($n) {
@for $i from 1 through $n {
:nth-child(#{$i}) {
grid-area: g#{$i - 1};
}
}
}
CSS 내부에서도 for문을 사용할 수 있다. 위는 하위 모든 요소들에 특정 css를 적용시키는 구문이다.
@import
변수나 mixin들을 별도로 모아서 파일로 생성하고, 다른 파일에서 이를 @import 해서 사용할 수 있다.
@import 'constants.scss';
Button {
color : $red
}
classNames
import './Button.scss';
import classnames from 'classnames';
//...rest는 입력받은 나머지 속성들
function ScssButton({ children, size, color, outline, fullWidth, ...rest }) {
console.log({ outline }); //outline : true
return(
<button
className={classNames('Button', size, color, { outline, fullWidth })}
{...rest}>
{children}
</button>
)
}
//호출
return (
...
<ScssButton size="small" color="gray", outline, fullWidth, onClick=....>
SAMPLE
</ScssButton>
...
classNames를 사용하면 변수 명을 쉽게 담을 수 있다. 마지막 parameter에 object 타입으로 위와 같이 정의해주면
변수 (outline, fullWidth)가 true면 해당 클래스명이 포함된다. classnames를 import 해야한다.
Module 파일
*.module.scss와 *.scss의 형식으로 구분 할 수 있다. 전자의 경우 특정 컴포넌트나 페이지에만 적용할 때 사용하는 형식이고, 후자는 애플리케이션 전체에 대해 적용할 때 사용한다 (최상단에서 import 해야한다)
'React > CSS&HTML' 카테고리의 다른 글
[HTML/CSS] 기초 문법 (0) | 2022.04.16 |
---|---|
[CSS] scroll 영역의 크기를 100%로 만드는 방법 (1) | 2021.11.19 |