[SASS] 01. 내가 보려고 작성한 SASS 문법(SCSS)

Jin·2021년 12월 3일
0

SASS

목록 보기
1/1
post-thumbnail

편의상 scss로 지칭

1. 설치 및 세팅

  1. 터미널에서 아래의 명령어를 입력하여 설치
  • $ npm i -g sass
  • sass-project 디렉토리 생성하고 트랜스파일링할 scss 파일을 생성
  • 트랜스파일링할 sass 파일의 경로와 트랜스파일링 후 생성될 css파일의 경로 지정
  • $ sass foo.sscss:foo.css
  • npm scripts를 사용하면 매번 긴 명령어를 입력하지 않아도 된다. 만약 프로젝트 디렉토리에 package.json 파일이 없다면 $ npm init 명령어로 파일 생성
{
  "name": "natours",
  "version": "1.0.0",
  "description": "Landing page for natours",
  "main": "index.js",
  "scripts": {
    "watch:sass":"sass sass/main.scss css/style.css -w",
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "node-sass": "^6.0.1"
  }
}

마지막 -w를 붙이면 scss가 변경이 될때마다 자동으로 트랜스파일링이 된다.
이제 $ npm run watch:sass 로 트랜스파일링이 가능하다.

2. 문법

SASS와 SCSS의 문법은 차이점이 있지만 본인은 SCSS가 더 직관적이고 사용하기 편하므로 SCSS문법 기준으로 작성을 하겠다.

@import

  • 1개의 css파일에 모든 스타일을 기술하면 유지보수가 힘들고 가독성이 좋지 않기때문에 기능(7:1패턴)에 따라 css 파일을 분리하는게 좋다.

7:1 패턴에 대해 알아보기 => https://sass-guidelin.es/ko/#section-37

  • scss 파일명의 선두에는 _를 붙인다.
  • import를 할 경우 _와 확장자는 생략 가능하다.
//main.scss

@import 'abstracts/functions';
@import 'abstracts/mixins';
@import 'abstracts/variables';

1) 주석(Comment)

기존의 CSS는 /* ... */를 사용하였지만 scss는 Javascript 스타일의 주석도 // 사용이 가능하다.

2) 데이터 종류(Data Types)

데이터설명예시
Numbers숫자1, .82(0.82와 같음), 30px, 2rem
Strings문자bold, absolute, "/img/nat-1.jpg"
Colors색상black, #fff, rgba(0,0,0,.5)
Booleans논리true, false
Null프로퍼티값에 값이 null인 변수가 지정되면 트랜스파일링 되지 않는다.null
Lists공백이나 ,로 구분된 값의 목록(a, b, c), a b
MapsKey:value 형태(apple:a, orange:o, vaseline:v)

3) 중첩 기능(Nesting)

  • 기존의 CSS에서의 자식 태그 선택
.section .list{
    padding:20px;
    }

.section .list li {
    color: red;
}
  • scss에서의 자식 태그 선택
.section{
	.list{
    padding:20px;
   	li{
    color: red;
   }
 }
  • 중첩된 속성
.box {
	font: {
    	weight: bold;
        size: 20px;
    };
    margin: {
    	top: 10px;
        right: 20px;
    };
    padding: {
    	top: 10px;
        left: 2px;
    };
`

상위 선택자 참고(Ampersand)

중첩 안에서 &를 사용하여 상위 선택자를 참조하여 선택

<!-- html -->

<header class='header'>
  <div class="header__logo-box">
    <p class='header__logo-box--paragraph'>nice</p>
    <img class='header__logo' src="./img/logo-white.png" alt="logo-white">
  </div>
  <div class="header__text-box">
  </div>
</header>

SCSS

.header{
	padding: 3rem;
    
	&__logo-box{
    		margin: 2rem;

        &__paragraph{
        	color: red;
        }
    }
    &__text-box{
    	background-color: #fff;
    }
}

4) 변수(Variables)

  • variable.scss 파일을 하나 만들어서 모든 변수들을 거기서 정의해주고 사용하면 편하다.
$color-primary: #55c57a;
$color-primary-light: #7ed56f;
$color-primary-dark: #28b485;

$grid-width:114rem;
$gutter-vertical:8rem;
$gutter-vertical-small:6rem;

.row{
	width: $grid-width;
    margin: $gutter-vertical 0;
    color : $color-primary;
 }
  • 블록 내에서도 변수생성이 가능하지만, 선언된 블록 내에서만 유효 범위를 가진다.
.row {
 	$color-primary: #55c57a;
   	bacground-color : $color-primary;
 }

 .header{
 	background-color : $color-primary;
 }

5) 문자 보간(Interpolation)

#{$변수명} 을 사용하여 코드의 어디든지 변수값을 넣을 수 있다.

.col-1-of-2 {
    width: calc((100% - #{$gutter-horizontal})/2);
  }

6) !default

  • !default 는 할당되지 않은 변수의 초기값을 설정
  • 이미 값이 할당되어 있는 변수에 !default를 사용하면 적용되지 않는다.
$content : null;
$content: 'Non-null content' !default;

.row {
	content : $content; // 'Non-null content'
 }

연산

산술 연산자와 비교 연산자는 Python이랑 같다.

1) 숫자

  • 일반적으로 절대값을 나타내는 px 단위로 연산을 한다. 상대적 단위(%,em,vw) 등은 calc() 로 연산해야 한다.
  • 또한 연산자의 왼쪽 값을 기준으로 단위가 설정 된다.
width: 50% - 20px; // 연산 불가
width: calc(50%-20px) // 가능

$width: 100px;

.row{
	width: $width + 10 //110px
}

.header{
	width: $width + 10in // 1060px
}
  • CSS에서의 / 은 나눗셈의 의미가 아니라 값을 구분하는 의미를 갖기 대문에 / 연산자를 사용하기 위해 몇가지 조건이 필요하다.
    • 변수에 대한 사용
    • 괄호 내에서 사용
    • 다른 연산의 일부로 사용
width: $width / 2;            // 변수에 대해 사용 → width: 500px;
height: (500px / 2);          // 괄호 내에서 사용 → height: 250px;
margin-left: 5px + 8px / 2px; // 다른 연산의 일부로서 사용 → margin-left: 9px;

조건과 반복

1) if

  • 기본적으로 JavaScript와 유사하게 동작하기에 이해하는데 있어 큰 어려움이 없었다.
p {
  @if $type == ocean {
    color: blue;
  } @else if $type == matador {
    color: red;
  } @else if $type == monster {
    color: green;
  } @else {
    color: black;
  }
}
  

2) @for

@for $i from i through 3 {
	.item-#{$i} { width: 2em * $i;}
}

// 트랜스 파일링 결과

.item-1 {
  width: 2em;
}
.item-2 {
  width: 4em;
}
.item-3 {
  width: 6em;
}

3) @each

  • list 또는 mpa의 요소에 대한 반복을 실시한다.
@each $theme in $themes {
  .section-#{$theme} {
    background-color: map-get($colors, $theme);
  }
}

//map 에서 반복을 할 때는, 일관성을 강제하기 위해 언제나 $key $value를 변수 이름으로 사용하길 권장한다.
@each $key, $value in $map {
  .section-#{$key} {
    background-color: $value;
  }
}

@Mixins

  • Sass 언어에서 가장 많이 사용되는 기능 중 하나이다.
  • 간결성이 가장 중요하며 Mixin이 20줄을 넘게되면 더 작은 덩어리로 수정해야하는것을 권장한다.
  • python의 function 과 유사하다고 생각하면 이해하기 쉽다. function과 마찬가지로 인자도 전달해줄 수 가 있다.
  • 사용시에는 @include mixin이름;
//mixin 생성

@mixin absCenter {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.row {
   @include absCenter;
 }
  • 인자 전달

.row{
   @include respond(phone){
	margin: 5px;
 }
}

@mixin respond($breakpoint) {
  @if $breakpoint==phone {
    @media only screen and (max-width: 37.5em) {
      @content
    }; 
  }

  @if $breakpoint==tab-port {
    @media only screen and (max-width: 56.25em) {
      @content
    };
  }
  

 





profile
내가 다시 볼려고 작성하는 블로그. 아직 열심히 공부중입니다 잘못된 내용이 있으면 댓글로 지적 부탁드립니다.

0개의 댓글