[SCSS] 기본 문법 정리

주석

/* 주석입니다 */

 

 

 

중첩

.parent {
color: red;
.child {
background-color: blue;
}
}

 

 

 

상위 선택자 참조 "&"

.parent {
/* 여기서 &는 .parent 를 가리킴 */
}

 

 

 

상위 선택자 무시 "@at-root"

.parent {
$w: 100px;
@at-root .parent2 {
...
}
}

상위 선택자에 선언된 값은 쓰고싶은데 .parent의 자식은 아닐 때 사용한다.

 

 

 

변수

$변수명: 값;
/*ex*/
$red: #ff0000;
$header-color: $red;

여타 프로그래밍 언어와 동일하게 중괄호 내에서 선언 시 그 밖에서는 사용 불가.

 

 

 

글로벌 변수 !global

$변수명: 값 !global;

 

 

 

있으면 그대로 없으면 새 걸로 !default

$my-color: red;
$my-color: blue !default; /* $my-color is red */

 

 

 

변수 할당 {}

$my-color: red;
.{$my-color}-header { /* .red-header class */
}

 

 

 

import

일반 css 파일: 확장자 반드시 지정

scss 파일: import할 파일 이름 앞에 언더바(_)를 붙인 뒤 (_header.scss) 메인에서 import.

@import "header";

 

 

 

★ @mixin

스타일 재사용을 위한 기능.

@mixin orange-box {
width: 100px;
height: 100px;
color: white;
font: {
size: 2rem;
weight: bold;
}
background-color: orange;
}
.box {
@include orange-box();
}

box class 속성 안에 orange-box에 선언한 속성이 그대로 들어간다.

 

다음과 같이 별도의 파라미터를 받아 적용할 수도 있다.

colon(:)을 통해 default parameter를 적용할 수도 있다.

@mixin color-box($color: orange) {
width: 100px;
height: 100px;
color: white;
font: {
size: 2rem;
weight: bold;
}
background-color: $color;
}
.blue-box {
@include color-box(blue);
}
.orange-box {
@include color-box();
}

 

 

 

@function (함수)

style을 반환하는 mixin과 달리, value를 반환한다.

또한 mixin과 달리 @import를 명시하지 않고 그냥 사용한다.

@function get-size($size: 2rem) {
@return ($size*3)/2;
}
.box {
@include color-box();
font-size: get-size();
}

box class의 font-size는 (2*3)/2 rem인 3rem으로 나온다.

 

 

 

if (조건 함수)

@mixin set-color($w: 100px) {
background-color: if($w > 100px, orange, blue);
}

 

 

 

@if (조건문)

$is-mobile: true; // boolean 자료형도 사용 가능
.box {
@if $is-mobile {
// 모바일 화면에 대한 처리
}
@else {
// 데스크탑 화면에 대한 처리
}
}

 

 

 

@for (반복문)

주로 nth-child와 함께 사용된다.

@for $i from 1 through 5 {
.box:nth-child($i) {
color: red;
}
}