CSS 전처리기는 자신만의 특별한 syntax를 가지고 CSS를 생성하도록 도와주는 프로그램으로써, mixin, nesting selector, inheritance selector 등등을 제공함으로써 CSS 구조를 가독성있고 유지보수하기 좋도록 도와준다.
ㅤ
SASS,LESS,Stylus,PostCSS등 여러가지가 있지만, 여기서는 가장 널리 사용되는SASS에 대해서 공부해본다.
SASS는 Syntactically Awesome Style Sheets의 줄임말이며, SCSS는 Sassy CSS의 줄임말이다. SCSS는 SASS의 모든 기원을 지능하면서 CSS 구문과 완전히 호환되도록 만들어져, 훨씬 사용에 편리하다. 따라서 SCSS를 배워보도록 하자.
ㅤ
참고로 SASS/SCSS 자체로는 브라우저에 적용할 수 없고, 컴파일러를 통해 CSS파일로 컴파일해야만 브라우저에서 동작한다.
npm install -g node-sass: npm 모듈로 node-sass를 설치
node-sass style.scss style.css: style.scss 파일을 style.css로 컴파일
node-sass -w style.scss style.css: style.scss가 변경되었을 때 자동으로 style.css로 컴파일
부모요소를 반복적으로 기술하지 않고 사용이 가능하다.
// CSS .header{ width: 100%; } .header div{ height: 100%; } .header div:hover{ margin: 10%; } ㅤ // SCSS .header{ width: 100%; div{ height: 100%; &:hover{ margin: 10%; } } }
$를 사용해서 공통된 속성들을 재활용 할 수 있다.$header-color: #d9d9d9; ㅤ .header{ color: $header-color; }
@mixin을 사용하여 공통된 속성의 묶음을 재활용 할 수 있다.@mixin header-style{ width: 100%; height: 100%; } ㅤ .header{ @include header-style; }
@import를 통해 CSS 파일을 가져올 수 있다.@import 'header.scss'
@if로 조건 분기가 가능하다.$theme: wave; ㅤ header{ @if $theme == wave{ color: blue; } @else if $theme == grass{ color: green; } @else { color: white; } }
@for로 반복문 사용이 가능하다@for $i from 0 through 3{ .block-#{$i}{ width: 30% * $i; } }
myPage 프로젝트에 적용시켜 보았다.
$theme__color--normal: #d9d9d9; $font__hover--weight: 700; ... @mixin font-style{ font-family: 'Roboto', 'Nanum Gothic', sans-serif; font-size: 15px; } ... input{ &[type=submit]{ @include font-style; background: none; border: none; padding: 0; &:hover{ font-weight: $font__hover--weight; } } } ...