logo
Search검색어를 포함하는 게시물들이 최신순으로 표시됩니다.
    Table of Contents
    [SCSS] SCSS의 시작, nesting, variable, lists/maps

    이미지 보기

    [SCSS] SCSS의 시작, nesting, variable, lists/maps

    • 22.06.24 작성

    • 22.06.30 수정

    • 읽는 데 7

    TOC

    Sass란?

    • CSS 전처리기의 하나
    • 개발은 Sass를 기반으로 한 후, CSS로 compile & export
    • 브라우저는 Sass 파일을 직접 읽지 못함

    SCSS의 시작

    추천 VSC extension: Live Sass Compiler


    npm 시작

    원하는 폴더 경로에서 아래 명령어 작성

    $ npm -v 
    // 버전이 출력되면 npm 설치가 되어있는 것
    
    $ npm init -y
    // 기본 세팅(폴더명이 한글이면 에러 발생 가능)
    
    $ npm i node-sass
    // sass를 사용할 수 있게 하는 lib
    

    package.json

    • npm init -y 명령어로 package.json이 생성
    • 해당 파일 내에 아래 코드 추가
    "scripts": {
      "test": "echo \"Error: no test specificed\" && exit 1",
      "sass": "node-sass -w -r scss/style.scss src/style.css"
    },
    
    • 위의 코드를 추가하면 scss 파일 내의 style.scss에서 src/style.css로 컴파일할 수 있도록 설정
    • 파일의 이름 또는 경로는 임의로 변경 가능. 위의 코드는 예시
    • node_modules와 같은 레벨에서 scss/style.scss 파일 생성

    -w, -r은 무슨 옵션이죠?

    -w, --watch                Watch a directory or file
    -r, --recursive            Recursively watch directories or files
    

    -w

    • 해당 옵션이 없을 때는 sass파일을 수정할 때마다 sass 실행
    • -w를 옵션으로 추가하게 되면 sass가 꺼지지 않고 계속적으로 sass 파일의 변경사항을 감시
    • 저장할 때마다 자동으로 컴파일

    -r

    • -r은 -w와 같이 감시
    • 차이점은 -w만 추가했을 경우에 메인 파일만 감시하고 그 외에 파일들은 감시하지 않아서 변경 X
    • -r을 추가할 경우 메인파일에 import한 다른 파일도 함께 감시
    • 즉, 반드시 필요

    npm run

    $ npm run sass
    
    • package.json에 지정된 scss 파일을 compile

    모듈화

    // style.scss
    @import "variables";
    @import "mixin";
    @import "header";
    @import "main";
    
    <!-- 파일구조 -->
    _header.scss
    _main.scss
    _mixin.scss
    _variables.scss
    style.scss
    
    • 모듈에 언더바가 붙는 이유: sass에게 모듈 파일이 main 파일의 일부임을 알려줌
    • @import 문법을 활용해 모듈 호출 가능
    • CSS 컴파일은 언더바가 없는 scss 파일들만!

    Nesting(중첩)

    개념

    /* css의 경우 */
    nav {
      background: white;
      padding: 10px;
      height: 50px;
    }
    
    nav:hover {
      background: green;
    }
    
    nav ul {
      display: flex;
      list-style: none;
      justify-content: flex-end;
    }
    
    nav ul li {
      color: black;
      margin-right: 10px;
    }
    
    • 기존 css는 class나 id가 없는 tag의 경우 구분이 헷갈림
    • 상속된 자식 요소에게 스타일을 적용하려 하면 최상위 선택자를 반복 선언해야 함

    /* scss의 경우 */
    nav {
      background: white;
      padding: 10px;
      height: 50px;
    
      &:hover {
        background: green;
      }
    
      ul {
        display: flex;
        list-style: none;
        justify-content: flex-end;
    
        li {
          color: black;
          margin-right: 10px;
        }
      }
    }
    
    • 계층 구조가 눈에 잘 보임
    • 반복 감소

    지나친 코드 중첩은 지양

    • 가독성을 오히려 떨어트린다.
    • 컴파일 과정에서 불필요한 선택자가 사용될 수 있다.

    속성 nesting

    .add-icon {
      background-image: url("./assets/arrow-right-solid.svg");
      background-position: center center;
      background-repeat: no-repeat;
      background-size: 14px 14px;
    }
    
    // scss
    .add-icon {
      background : {
        image: url("./assets/arrow-right-solid.svg");
        position: center center;
        repeat: no-repeat;
        size: 14px 14px;
      }
    }
    

    앰퍼샌드(ampersand)

    & 표시를 통해 반복 제거

    .absolute-perfect-box:focus {}
    .absolute-perfect-box:hover {}
    .absolute-perfect-box:active {}
    
    .absolute-perfect-box {
      &:focus {}
      &:hover {}
      &:active {}
    }
    
    • **&**는 상위에 있는 부모선택자를 의미
    • selector를 한 번만 선언할 수 있어 반복 제거
    • 긴 selector인 경우에 더더욱 유리

    클래스명이 다른 경우도 사용

    .absolute-perfect-box-red {
      background: red;
    }
    .absolute-perfect-box-blue {
      background: blue;
    }
    .absolute-perfect-box-green {
      background: green;
    }
    
    .absolute-perfect-box {
      &-red {
        background: red;
      }
      &-blue {
        background: blue;
      }
      &-green {
        background: green;
      }
    }
    

    변수

    개념

    • 유지보수를 위해 사용
    • 2번 이상 반복되는 경우 사용
    • 보통 폰트 색상, 사이즈, 간격 등의 값을 정의

    변수 사용 예시

    // 색상
    $red: #ee4444;
    $black: #222;
    $bg-color: #3e5e9e;
    $link-color: #red;
    $p-color: #282A36;
    
    // 폰트 사이즈
    $font-p: 13px;
    $font-h1: 28px;
    
    // 폰트
    $base-font: 'Noto Sans KR', sans-serif;
    
    body {
      background-color: $bg-color;
      font-size: $font-p;
      font-family: $base-font;
    }
    
    h1 {
      font-size: $font-h1;
      color: $black;
    }
    
    p {
      font-size: $font-p;
      color: $black;
    }
    

    Lists, Maps

    Lists

    • 쉼표, 공백, 일관성이 있는 **/**로 구분하여 생성
    • 빈 lists나 값이 하나인 경우에만 []또는()`을 사용하여 생성
    • index는 1부터 시작

    $sizes: 40px, 50px, 80px;
    $valid-sides: top, bottom, left, right;
    

    lists 관련 내장함수

    • append(list, value, [separator]): lists 값을 추가
    • index(list, value): lists의 값에 대한 index return
    • nth(list, n): lists의 index에 대한 값 return

    // scss
    $valid-sides: left, center, right;
    
    .screen-box {
      text-align: nth($valid-sides, 1);
    }
    
    // css
    .screen-box {
      text-align: left;
    }
    

    Maps

    객체와 같다. 키:값의 형태로 저장

    • key는 중복 불가, value는 중복 가능
    • 같은 카테고리의 변수들을 일일히 만들지 않기 위해 사용

    내장함수

    • map-get(map, key): key의 value return
    • map-keys(map): key 전체 return
    • map-values(map): value 전체 return

    Maps 사용 예시

    // scss
    $font-sizes: ("h1":45px, "h2": 19px, "p": 16px);
    
    section {
      h2 {
        font-size: map-get($font-sizes, "h1");
      }
    }
    
    // csss
    section h2 {
      font-size: 19px;
    }
    
    profile

    FE Developer 박승훈

    노력하는 자는 즐기는 자를 이길 수 없다