자주 사용하는 스타일링 방식은 다음과 같다.
css를 작성할 때 가장 중요한 점은 클래스를 중복되지 않게 만드는 것이다.
클래스 이름을 '컴포넌트 이름-클래스 형태'로 지으면 중복을 방지할 수 있다.
BEM네이밍 방식은 CSS방법론 중 하나로, 이름을 지을 때 일종의 규칙을 준수하여 해당 클래스가 어디에서 어떤 용도로 사용되는지 명확하게 작성하는 방식이다.
sass는 css전처리기로 복잡한 작업을 쉽게 할 수 있도록 해주고, 스타일 코드의 재활용성을 높여줄 뿐만 아니라 코드의 가독성을 높여 유지 보수를 쉽게 해준다.
sass에서는 .scss와 .sass의 두 가지 확장자를 지원한다.
// sass
$font-stack: Helvetica, sans-serif
$primary-color: #333
body
font: 100% $font-stack
color: $primary-color
// scss
$font-stack: Helvetica, sans-serif;
$primary-color: #333;
body {
font: 100% $font-stack;
color: $primary-color;
}
sass확장자는 중괄호와 세미콜론을 사용하지 않는다.
반면 scss는 기존 css방식과 문법이 크게 다르지 않다.
보통 scss문법이 더 자주 사용된다.
한 번 Sass를 사용해보자. 우선 node-sass라는 라이브러리를 설치해야 한다. (sass를 css로 변환해준다) 다음 명령어로 설치하자.
$ yarn add node-sass
// SassComponent.scss
// 변수 사용하기
$red: #fa5252;
$orange: #fd7e14;
$yellow: #fcc419;
$green: #40c057;
$blue: #339af0;
$indigo: #5c7cfa;
$violet: #7950f2;
// 믹스인 만들기(재사용되는 스타일 블록을 함수처럼 사용할 수 있음)
@mixin square($size) {
$calculated: 32px * $size;
width: $calculated;
height: $calculated;
}
.SassComponent {
display: flex;
.box {
//일반 css에서는 .SassComponent .box와 마찬가지
background: red;
cursor: pointer;
transition: all 0.3s ease-in;
& .red {
// .red클래스가 .box와 함께 사용되었을 때
background: $red;
@include square(1);
}
&.orange {
background: $orange;
@include square(2);
}
&.yellow {
background: $yellow;
@include square(3);
}
&.green {
background: $green;
@include square(4);
}
&.blue {
background: $blue;
@include square(5);
}
&.indigo {
background: $indigo;
@include square(6);
}
&.violet {
background: $violet;
@include square(7);
}
&:hover {
// .box에 마우스를 올렸을 때
background: black;
}
}
}
// SassComponent.js
import React from "react";
import "../asset/SassComponent.scss";
const SassComponent = () => {
return (
<div className="SassComponent">
<div className="box red" />
<div className="box orange" />
<div className="box yellow" />
<div className="box green" />
<div className="box blue" />
<div className="box indigo" />
<div className="box violet" />
</div>
);
};
export default SassComponent;
// App.js
import React from "react";
import SassComponent from "./Component/SassComponent";
const App = () => {
return <SassComponent />;
};
export default App;
음 그런데 에러가 생겼다.
Node Sass version 6.0.1 is incompatible with ^4.0.0 || ^5.0.0.
찾아보니 CRA로 만들어진 프로젝트는 6.0.1 버전이랑 충돌나니 4.xx버전으로 다시 깔아야 하는 듯 하다.
//node-sass 삭제
$ yarn remove node-sass
//node-sass 4.14.0버전 설치
$ yarn add node-sass@4.14.0
다시 설치했더니 깔끔하게 실행된다.
