Sass(SCSS)

김병현·2022년 2월 16일
0

html_css

목록 보기
4/4

Sass(SCSS)

CSS는 개발규모가 커져갈수록 단순한 반복적인 코드가 유지보수를 어렵게 만든다는 단점이 있습니다. 이러한 단점을 보완하기 위해 변수, 조건문, 반복문 등 기능을 확장(Extension)하여 만들어진 Style Sheet 언어이자 전처리기입니다.

  • 전처리기 (Preprocessor) : 컴퓨터의 처리에 있어 수행하는 기능을 위해 사전 준비 계산을 행하는 프로그램

SCSS는 Sass를 CSS 문법과 호환되도록 새로운 문법을 도입해 만든 상위집합(Superset)이며 Sass 기능을 지원합니다.


설치방법

Nodejs(자바스트립트 개발 환경)의 패키지인 npm(Node Pakage Manager)를 이용하여 설치합니다.

  1. Nodejs 설치

  2. Sass 설치 : npm install -g sass

    • -g : -global. 전역 설치이며 즉, 특정 경로가 아닌 local에 설치한다는 의미
  3. Bundler "Parcel" 설치 : npm install -g parcel-bundler

    • Bundler란 Bundling을 실행하는 도구입니다. Bundling은 여러가지의 파일 중 종속되어 있거나 동일한 유형의 파일들을 하나의 파일로 묶는 과정을 의미힙니다. 예로 1번 파일에서 2번 파일의 함수를 호출해야 할 경우 1번파일에서 2번 파일을 불러오도록 합니다. 이런 Bundling을 통해 파일을 하나로 합쳐 네트워킹 요청 횟수도 줄어드는 효과가 있습니다.
    • Parcel : Bundling Modul(한번 사용했던 기능들을 쉽게 불러와 사용할 수 있도록 하나의 파일로 모아둔 방법)
  4. npm 구동 초기화

npm init -y
npm install --save-dev parcel-bundler
  1. npx(Pakage Runner)로 index.html을 parcel을 이용하여 컴파일 후 실행
    npx parcel index.html
  • npx : npm 5.2 버전 이상에 있는 패키지들을 쉽게 설치하고 실행할 수 있도록 도와주는 도구입니다. 전역으로 설치하는 패키지가 아니라 특정 프로젝트에만 설치되는 패키지의 경우 npm을 레지스트리에 접근해서 실행시키고 설치합니다.
  1. 실행 후 http://localhost:1234를 ctrl + 클릭하여 웹브라우저를 통해 확인

< ! 컴파일러 설치도 필요하지만 npm pakage에 기본적으로 Dart sass라는 컴파일러가 포함되어 있기 때문에 별도로 설치할 필요가 없습니다. >

node --version   #nodejs 버전 확인
npm --version   #npm 버전 확인
sass --version 또는 npm show sass version   #sass 버전 확인

명령어

sass *.scss *.css   # .scss 파일을 .css 파일로 (일회성)컴파일
sass --watch *.scss *css   # .scss 파일을 .css 파일로 (지속적)컴파일
sass --watch 폴더:폴더   # 폴더를 지정하여 컴파일
sass --no-source-map *.scss *css   # .map 파일을 생성하지 않고 컴파일

주석

.container {
  $size: 100px;
  .box {
    width: $size;
   /* height: $size; */   # 주석. 컴파일 파일에 포함됨
   // background-color: orange; //   # 주석. 컴파일 파일에 포함되지 않음
  }
}

문법

1. 중첩 (nesting)

/* scss */

.section {
   width: 100%;
   .list {
      padding: 20px;
      li {
         float: left;
      }
   }
}
---
/* css */

.section {
  width: 100%;
}
.section .list {
  padding: 20px;
}
.section .list li {
  float: left;
}

# scss에서 부모 tag(or class 등) 안에 자식 tag들을 작성할 경우 중첩(부모 tag)되는 부분은 작성하지 않아도 css에서는 자동적으로 부모 tag가 각각 작성됨

2. 치환 (ampersand)

/* scss */

.btn {
   width: 110px;
   height: 100px;
   &:active {
      color: red;
   }
}

.view {
   &-medium {
      font-style: 13px;
   }
   &-large {
      font-style: 15px;
   }
}
---
/* css */

.btn {
  width: 110px;
  height: 100px;
}
.btn:active {
  color: red;
}

.view-medium {
  font-style: 13px;
}
.view-large {
  font-style: 15px;
}

# scss에서 tag(or class 등) 내부에 있는 속성들에 대해서 tag 명 대신 "&"으로 대체하여 입력 가능함

3. at-root (@)

/* scss */

.section {
   $width: 100px;
   $height: 200px;

   width: $width;
   height: $height;

   .item {
      width: $width;
      height: $height;
   }

   @at-root .box {
      width: $width;
      height: $height;
   }
}
---
/* css */

.section {
  width: 100px;
  height: 200px;
}

.section .item {
  width: 100px;
  height: 200px;
}

.box {
  width: 100px;
  height: 200px;
}

# 중첩 안에서 생성하되 중첩을 벗어나고 싶은 경우 @ (at-root)를 사용함. 특정 범위 안에서 선언된 변수(= 지역변수)는 정의된 범위 밖에서 사용할 수 없기 때문에 지역변수 안의 변수를 사용하면서 중첩을 벗어나고 싶은 경우에 유용함

4. namespace

/* scss */

.box {
   font: {
      weight: bold;
      size: 10px;
      family: sans-serif;
   }
}
---
/* css */

.box {
  font-weight: bold;
  font-size: 10px;
  font-family: sans-serif;
}

# 속성 이름중 중첩되는 부분은 생략하고 작성이 가능함

5 - 1. 변수 (variable)

/* scss */

$color-primary: tomato;
$url-images: "/images/";
$w: 200px;

.box {
   width: $w;
   margin-left: $w;
   background: $color-primary url($url-images + "nice.jpg");
}
---
/* css */

.box {
  width: 200px;
  margin-left: 200px;
  background: tomato url("/images/nice.jpg");
}

# $"변수이름": 변수값;을 선언 후 속성값으로 $"변수이름"을 사용하여 코드의 재사용이 가능

5 - 2. 변수의 범위

/* scss */

$size: 20px;   # 전역변수

.box1 {
   $color: toamto !global;   # 지역변수 (!global 선언 후에는 전역변수)
   background: $color;
}

.box2 {
   background: $color;
}
---
/* css */

.box1 {
  background: toamto;
}

.box2 {
  background: toamto;
}

# 전역변수는 모든 선택자에서 사용이 가능하지만 지역변수는 선언한 선택자 안에서만 사용이 가능. 하지만 지역변수에 !global 속성을 사용하면 전역변수로 전환되어 모든 선택자에서 사용 가능

< ! 지역변수에 !global을 사용할 경우, 꼭 !global을 먼저 선언할 것. !global을 사용할 속성자 뒤에 사용하면 css의 cascading 성질에 따라 !global이 사용된 지역변수를 찾기 전에 사용된 속성자를 먼저 찾아버리기 때문에 에러 발생 >

5 - 3. 변수 재할당 (variable reassignment)

/* scss */

$red: red;
$blue: blue;

$color-primary: $blue;
$color-danger: $red;

.box {
   color: $color-primary;
   color: $color-danger;
}
---
/* css */

.box {
  color: blue;
  color: red;
}

# 변수에 변수를 할당할 수 있음

6. 변수값 재선언

/* scss */

$color-primary: red;

.box {
   $color-primary: blue;
   background-color: $color-primary;
}
---
/* css */

.box {
  background-color: blue;
}
# 기존 선언된 변수의 값을 변경을 희망하거나 원하는 값으로 다시 선언하여 사용 가능

7. 변수값 초기설정 (default)

/* scss */

$color-primary: red;

.box {
   $color-primary: blue !default;
   background-color: $color-primary;
}
---
/* css */

.box {
  background-color: red;
}

# 6. 변수값 재선언 예시와 같이 변수값을 재선언하였어도 !default 속성을 사용하면 변수의 초기 선언값으로 초기화됨

8. 문자열 보관 (unquote)

/* scss */

$insert: unquote("Jeju Myeongjo");
@import url("http://fonts.googleapis.com/earlyaccess/jejumyeongjo.css?font-family=#{$insert}");
---
/* css */

@import url("http://fonts.googleapis.com/earlyaccess/jejumyeongjo.css?font-family=Jeju Myeongjo");

# unquote() 함수를 활용해 문자열을 보관하여 #{}를 이용해서 코드에 변수값을 사용 가능. unquote() 함수는 문자에서 따옴표를 제거하는 기능이 있기 때문에 따옴표 작성할 필요없음 

9. @mixin @include

/* scss */

@mixin size($w: 200px, $h: 300px) {
   width: $w;
   height: $h;
}

.box {
   @include size;
}

.box2 {
   @include size(150px, 250px);
}

.box3 {
   @include size($h: 500px);
}

.box4 {
   @include size;
}
---
/* css */

.box {
  width: 200px;
  height: 300px;
}

.box2 {
  width: 150px;
  height: 250px;
}

.box3 {
  width: 200px;
  height: 500px;
}

.box4 {
  width: 200px;
  height: 300px;
}

# Sheet 재사용할 CSS 그룹을 정의하는 기능. @mixin(선언하다) @include(포함하다)으로 변수값 사용가능. 변수값 재선언도 가능

10. Sass media query

/* variable */
$breakpoint-mobile: 375px;
$breakpoint-tablet: 768px;
$breakpoint-desktop: 1200px;

/* @mixin */

@minxin mobile {
	@media (min-width: #{$break-mobile}) and (max-width: #{$breakpoint-tablet - 1px}) {
    @content;
  }
}

@minxin tablet {
	@media (min-width: #{$break-tablet}) and (max-width: #{$breakpoint-desktop - 1px}) {
    @content;
  }
}

@minxin desktop {
	@media (min-width: #{$break-mobile}) {
    @content;
  }
}

/* include */

@include mobile {
  .img-card {
    width: 100px;
  }
}

@include tablet {
  .img-card {
    width: 200px;
  }
}

@include desktop {
  .img-card {
    width: 300px;
  }
}
profile
Without haste, but without rest.

0개의 댓글