Sass 기초
변수와 중첩
Sass 변수는 $ 접두사를 사용합니다. 중첩은 HTML 구조를 그대로 반영합니다. &는 부모 선택자를 가리킵니다. 색상 조작에는 lighten()/darken()을 사용하세요.
// SCSS syntax ($var)
$primary-color: #3498db;
$font-stack: -apple-system, sans-serif;
body {
font-family: $font-stack;
color: $primary-color;
a {
color: lighten($primary-color, 20%);
&:hover {
color: darken($primary-color, 10%);
}
}
}SCSS와 들여쓰기 문법
SCSS(.scss)는 CSS의 상위 집합이라 유효한 CSS 파일은 모두 유효한 SCSS입니다. Sass(.sass)는 중괄호와 세미콜론을 없애고 들여쓰기에 의존합니다. SCSS가 더 인기 있고 마이그레이션도 쉽습니다. 하나를 선택해 프로젝트 안에서 일관되게 사용하세요.
// SCSS (.scss) - uses braces and semicolons
.box {
width: 100px;
height: 100px;
}
// Sass (.sass) - indentation-based, no braces/semicolons
.box
width: 100px
height: 100px
// Both compile to the same CSS
// .box { width: 100px; height: 100px; }주석
// 주석은 조용히 사라집니다(출력에서 제거). /* */ 주석은 컴파일된 CSS에 유지됩니다. /*! */ 주석은 압축/운영 모드에서도 유지되므로 라이선스나 중요 공지에 사용하세요. 내부 문서화에는 //를 사용하세요.
// Single-line comment - NOT compiled to CSS
/* Multi-line comment - compiled to CSS */
/*! Important comment - always kept even in compressed mode */
// Silent comment for developers
$base-font: 16px;
/*! Keep this copyright notice */
body { font-size: $base-font; }컴파일
Sass는 .scss/.sass를 .css로 컴파일합니다. --watch는 저장 시 자동 재컴파일합니다. 출력 스타일: expanded(기본, 읽기 쉬움), nested(들여쓰기), compact(한 줄에 규칙 하나), compressed(운영용 압축). 운영 환경에서는 파일 크기를 줄이려고 compressed를 사용하세요.
// Compile a single file
// $ sass input.scss output.css
// Watch for changes
// $ sass --watch input.scss:output.css
// Watch a directory
// $ sass --watch scss/:css/
// Compressed output
// $ sass --style=compressed input.scss output.css
// Four output styles: expanded, nested, compact, compressed
$width: 100px;
.box { width: $width; }선택자 상속 개요
Sass는 변수, 중첩, 믹스인, 상속, 함수, 제어 흐름을 추가하는 CSS 전처리기입니다. 반복을 줄이고(DRY 원칙) 큰 스타일시트를 관리 가능하게 만듭니다. 모든 Sass 기능은 표준 CSS로 컴파일됩니다.
// Sass adds programming features to CSS:
// 1. Variables ($var)
// 2. Nesting
// 3. Mixins (@mixin / @include)
// 4. Inheritance (@extend)
// 5. Functions (@function)
// 6. Control directives (@if, @for, @each, @while)
// 7. Partials & Modules (@use, @forward)
// These features help keep stylesheets DRY and maintainable.
$radius: 4px;
.card { border-radius: $radius; }변수와 데이터 타입
변수 선언과 범위
블록 밖에서 선언한 변수는 전역입니다. 블록 안에서 선언한 변수는 그 블록에 지역적입니다. 지역 변수는 같은 이름의 전역 변수를 가립니다. 전역 네임스페이스를 오염시키지 않으려면 지역 변수를 사용하세요.
$color: #333; // global scope
$padding: 10px; // global
.block {
$local-color: #fff; // local to .block
color: $local-color;
padding: $padding; // can read globals
}
// $local-color is NOT available here
// .other { color: $local-color; } // ERROR!default 플래그
!default는 변수가 null이거나 정의되지 않았을 때만 값을 할당합니다. 사용자는 라이브러리를 가져오기 전에 변수를 설정해 라이브러리 기본값을 덮어쓸 수 있습니다. 설정 가능한 Sass 라이브러리와 디자인 시스템을 만드는 데 필수입니다.
// Only assign if the variable is not already defined
$base-color: #333 !default;
$base-color: #fff; // this wins (already? no - assigned above first)
// Useful in libraries/partials for user overrides
// _theme.scss
$primary: blue !default;
.button { background: $primary; }
// User config BEFORE importing
// $primary: red;
// @use 'theme'; -> button is red!global 플래그
!global은 블록(믹스인, 함수, 제어 지시문) 안에서 전역 범위에 명시적으로 할당합니다. Sass 3+부터 블록 안 할당은 기본적으로 지역입니다. 전역 변경은 코드를 이해하기 어렵게 만들 수 있으므로 !global은 드물게 사용하세요.
$count: 0;
@for $i from 1 through 3 {
$count: $count + $i !global;
}
// $count is now 6 (1+2+3)
.total { content: "#{$count}"; }
// Without !global, the assignment inside @for
// would create a local variable instead데이터 타입
Sass에는 7가지 데이터 타입이 있습니다: 숫자(단위 포함), 문자열, 색상, 불리언, null, 리스트, 맵. type-of()는 타입을 문자열로 반환합니다. 함수와 제어 지시문을 올바르게 사용하려면 타입을 이해하는 것이 필수입니다.
// Sass has 7 data types:
$number: 16px; // number (with optional unit)
$string: "Helvetica"; // string (quoted or unquoted)
$color: #3498db; // color
$boolean: true; // boolean (true/false)
$null: null; // null (no value)
$list: 10px 20px 30px; // list (space or comma separated)
$map: (key: value); // map (key-value pairs)
// Type checking
type-of($number) // number
type-of($list) // list
type-of($map) // map보간 #{}
#{} 보간은 변수를 선택자, 속성 이름, 문자열 등 일반 변수가 허용되지 않는 곳에 주입합니다. 값에서만 동작하는 $var와 달리 #{}는 거의 어디서나 동작합니다. 어떤 값이든 문자열 표현으로 변환합니다.
$name: "user";
$version: 2;
// Use #{} to insert variables into selectors and strings
.#{$name}-avatar { background: url("/img/#{$name}.png"); }
// In property names and values
.icon-#{$name} {
content: "v#{$version}";
}
// Interpolation in @media and @include
@media (max-width: #{$version * 100}px) {
body { font-size: 14px; }
}중첩
기본 중첩
중첩을 쓰면 HTML 계층을 그대로 반영하는 선택자를 작성해 부모 선택자 반복을 피할 수 있습니다. 컴파일된 CSS는 하위 선택자를 만듭니다. 가독성은 좋아지지만 과도하게 쓰면 선택자가 지나치게 구체적이 되므로 중첩은 최대 3-4단계로 유지하세요.
// SCSS nesting mirrors HTML structure
.nav {
background: #333;
ul {
list-style: none;
margin: 0;
li {
display: inline-block;
}
}
a {
color: white;
text-decoration: none;
}
}
// Compiles to: .nav {...} .nav ul {...} .nav ul li {...} .nav a {...}깊은 중첩(안티 패턴)
깊은 중첩은 덮어쓰기 어렵고 브 라우저 매칭이 느린 길고 지나치게 구체적인 선택자를 만듭니다. 경험칙: 3-4단계 넘게 중첩하지 마세요. 깊은 구조는 유지보수를 위해 BEM 스타일의 명시적 클래스로 평탄화하세요.
// AVOID: overly deep nesting
.header {
.nav {
> ul {
li {
a {
span { // 5 levels deep!
color: red;
}
}
}
}
}
}
// Compiles to: .header .nav > ul li a span
// Too specific - hard to override, slow to match
// BETTER: flatten with classes
.header-nav-link-text { color: red; }중첩 속성
중첩 속성은 속성 네임스페이스 뒤에 콜론(font:, border:, margin:)을 붙여 관련 하위 속성을 묶습니다. 접두사 반복을 피할 수 있으며 순전히 문법적 편의 기능입니다. font-family, border-top 같은 표준 CSS 속성으로 컴파일됩니다.
.icon {
// Shorthand for font-family, font-size, font-weight...
font: {
family: "Arial";
size: 14px;
weight: bold;
}
// border-top, border-right, etc.
border: {
top: 1px solid #ccc;
bottom: 2px dashed #999;
}
}
// Compiles to: font-family, font-size, font-weight, border-top, border-bottom미디어 쿼리 중첩
규칙 안에 @media 쿼리를 중첩하면 반응형 스타일이 컴포넌트와 함께 위치해 유지보수가 좋아집니다. 컴파일된 CSS는 @media를 최상위로 끌어올립니다. 미디어 쿼리를 파일 곳곳에 흩뿌리는 것보다 가독성이 크게 좋아집니다.
.container {
width: 100%;
// Media query nested inside the rule
@media (min-width: 768px) {
width: 720px;
}
@media (min-width: 1024px) {
width: 960px;
}
}
// Compiles to:
// .container { width: 100%; }
// @media (min-width: 768px) { .container { width: 720px; } }
// @media (min-width: 1024px) { .container { width: 960px; } }중첩에서 선택자 목록
쉼표로 구분된 선택자 목록을 중첩하면 Sass가 각 항목을 부모와 결합합니다. 각 조합을 직접 쓰는 것보다 깔끔합니다. &를 중첩 목록 안에서 사용해 여러 부모에 클래스/수정자를 한 번에 붙일 수도 있습니다.
.btn {
// Comma creates a selector list
.icon,
.label {
color: white;
}
}
// Compiles to:
// .btn .icon, .btn .label { color: white; }
// Nesting a list with &
.card,
.panel {
&.active { border-color: blue; }
}
// .card.active, .panel.active { border-color: blue; }부모 선택자(&)
기본 부모 선택자
&는 부모 선택자를 가리키므로 의사 클래스(:hover, :focus), 의사 요소(::before), 수정자를 중첩할 수 있습니다. 관련 스타일을 함께 유지할 수 있습니다. &:hover는 .button:hover로 컴파일됩니다. &가 없으면 하위 선택자가 됩니다.
.button {
background: blue;
color: white;
// & refers to the parent (.button)
&:hover {
background: darkblue;
}
&:focus {
outline: 2px solid blue;
}
&::after {
content: "→";
}
}
// Compiles to: .button, .button:hover, .button:focus, .button::after&로 BEM 작성
&를 쓰면 BEM(Block Element Modifier) 이름을 간결하게 만들 수 있습니다. &__title은 부모에 __title을 붙여 .card__title을 만듭니다. &--featured는 수정자 클래스를 만듭니다. 블록 정의 안에서 BEM 클래스 생성을 DRY하고 일관되게 유지합니다.
// BEM methodology with parent selector
.card {
background: white;
&__title { // .card__title
font-size: 18px;
}
&__body { // .card__body
padding: 16px;
}
&--featured { // .card--featured
border-color: gold;
}
&--featured &__title { // .card--featured .card__title
color: gold;
}
}부모 선택자에 접미사 붙이기
중첩 선택자의 시작에 &를 두면 접미사가 부모에 붙어 .button-primary 같은 복합 선택자를 만듭니다. 변형 이름을 지을 때 유용합니다. 하지만 과도한 접미사 사용은 소스를 읽을 때 생성될 클래스 이름을 파악하기 어렵게 만들 수 있으니 주의하세요.
.button {
background: blue;
// Append suffix to parent
&-primary { background: darkblue; } // .button-primary
&-secondary { background: gray; } // .button-secondary
&-danger { background: red; } // .button-danger
// Combining with state
&-primary.is-active { font-weight: bold; }
}
// Generates: .button, .button-primary, .button-secondary, .button-danger역방향 중첩
중첩 선택자의 끝에 &를 두면 순서가 뒤집혀 부모가 하위 요소가 됩니다. .dark-theme .modal처럼 컴포넌트가 상위 문맥에 적응하는 문맥/테마 스타일에 완벽합니다. 문맥별 덮어쓰기를 컴포넌트 가까이에 유지할 수 있습니다.
.modal {
// & at the end - parent as descendant
.dark-theme & {
background: #222;
color: #eee;
}
.sidebar & {
width: 200px;
}
}
// Compiles to:
// .dark-theme .modal { background: #222; color: #eee; }
// .sidebar .modal { width: 200px; }
// Useful when parent is styled differently in a context한 선택자에 여러 &
한 선택자에서 &를 여러 번 사용할 수 있습니다. & + &는 형제 스타일링용 .button + .button을 만듭니다. 반복 요소 사이 간격과 복잡한 상태 기반 선택자에 강력합니다. 각 &는 전체 부모 선택자로 치환됩니다.
.button {
// Multiple & references in one selector
& + & { // .button + .button (adjacent sibling)
margin-left: 8px;
}
& ~ & { // .button ~ .button (general sibling)
margin-top: 4px;
}
&.active &__icon { // .button.active .button__icon
color: white;
}
.parent &.is-open &__content {
display: block;
}
}파셜(_partial 파일)
파셜 만들기
파셜은 앞에 밑줄이 붙은 Sass 파일입니다(예: _variables.scss). 밑줄은 Sass에 별도 CSS 파일로 컴파일하지 말라고 알려줍니다. 파셜은 메인 파일로 가져오기 위한 것입니다. 코드를 모듈화해 유지보수를 돕습니다.
// _variables.scss - partial file (underscore prefix)
$primary: #3498db;
$secondary: #2ecc71;
$font-base: 16px;
// _buttons.scss
.button {
background: $primary;
padding: $font-base / 2;
}
// Partials are NOT compiled to their own CSS file.
// The underscore tells Sass this is a partial.
// Import them into a main file:
// main.scss: @use 'variables'; @use 'buttons';파셜 이름 규칙
파셜은 앞에 밑줄을 붙인 설명적인 이름을 사용합니다. @use나 @import 문에서는 밑줄과 확장자를 생략합니다. Sass가 'variables'를 자동으로 _variables.scss로 해석합니다. 일관된 이름은 팀이 코드를 빨리 찾는 데 도움이 됩니다.
// Common partial naming patterns:
// _variables.scss - variables
// _mixins.scss - mixins
// _functions.scss - functions
// _reset.scss - CSS reset
// _base.scss - base styles
// _typography.scss - typography
// _buttons.scss - button component
// _header.scss - header component
// _footer.scss - footer component
// _mediaqueries.scss - media queries
// Import without the underscore or extension:
// @use 'variables';
// @use 'mixins';7-1 아키텍처 패턴
7-1 패턴은 널리 채택된 Sass 아키텍처입니다. 7개 폴더(abstracts, base, components, layout, pages, themes, vendors)와 하나의 main.scss 진입점으로 구성됩니다. 관심사를 분리해 큰 프로젝트에서도 잘 확장됩니다. 각 폴더의 파셜을 main.scss로 가져옵니다.
// 7-1 architecture: 7 folders, 1 main file
// sass/
// abstracts/ - variables, functions, mixins
// base/ - reset, typography, base styles
// components/ - buttons, cards, nav
// layout/ - header, footer, grid
// pages/ - home, about specific styles
// themes/ - theme definitions
// vendors/ - third-party
// main.scss - imports everything
// main.scss
// @use 'abstracts/variables';
// @use 'base/reset';
// @use 'components/buttons';
// @use 'layout/header';인덱스 파셜(_index.scss)
_index.scss(또는 _all.scss) 파셜은 폴더의 공개 API 역할을 하며 모든 파셜을 전달합니다. 덕분에 @use 한 번으로 폴더 전체를 가져올 수 있습니다. 새 파셜을 추가할 때 인덱스만 갱신하면 메인 파일은 그대로입니다. Sass 모듈 시스템의 패턴입니다.
// sass/components/_index.scss
// Forward all component partials from one entry point
@forward 'buttons';
@forward 'cards';
@forward 'nav';
@forward 'modal';
// Now in main.scss, one line imports everything:
// @use 'components';
// (resolves to components/_index.scss)
// This keeps the main file clean and lets
// you reorganize partials without touching main.scss파셜 모범 사례
모범 사례: 파셜 하나에 관심사 하나, 파일은 작게 유지(50-200줄), 명시적 의존성 관리를 위해 @use 사용, 순환 가져오기 회피. 파셜은 유지보수성과 재사용성을 높입니다. @use는 이전 @import와 달리 의존성을 명시적으로 만듭니다.
// 1. One concern per partial
// _buttons.scss -> only buttons
// _forms.scss -> only forms
// 2. Keep partials small and focused
// (50-200 lines is a good target)
// 3. Use @use (not @import) for explicit dependencies
// _card.scss
@use '../abstracts/variables' as *;
@use '../abstracts/mixins' as *;
.card {
background: $white;
@include card-shadow;
}
// 4. Avoid circular dependencies@import와 @use
@import(폐기됨)
@import는 전역 네임스페이스를 오염시키고, 파일을 여러 번 실행할 수 있으며, 프라이버시나 네임스페이싱을 제공하지 않아 폐기되었습니다. Sass는 @use와 @forward로 마이그레이션할 것을 권장합니다. 기존 @import 코드는 동작하지만 새 프로젝트에서는 마이그레이션해야 합니다.
// @import - the OLD way (deprecated in Sass 1.80+)
@import 'variables';
@import 'mixins';
@import 'buttons';
// Problems with @import:
// 1. Globals leak across files (no namespacing)
// 2. Each @import of the same file runs it again
// 3. No way to make members private
// 4. Extends and mixins can conflict
// Use @use instead (the modern module system)
$primary: blue;@use 기초(네임스페이스)
@use는 모듈을 한 번 로드하고 네임스페이스(기본값은 파일 이름)를 통해 멤버를 노출합니다. 멤버는 namespace.$var나 namespace.mixin-name()으로 접근합니다. 전역 오염과 이름 충돌을 막습니다. 각 모듈은 @use가 몇 번 나오든 한 번만 로드됩니다.
// _variables.scss
$primary: #3498db;
$radius: 4px;
// main.scss - @use creates a namespace (filename by default)
@use 'variables';
.button {
// Access via namespace::member
background: variables.$primary;
border-radius: variables.$radius;
}
// The namespace prevents naming collisions
// and makes dependencies explicitas와 함께 쓰는 @use
'as v'는 네임스페이스를 더 짧게 바꿉니다. 'as *'는 접두사 없이 멤버를 현재 범위에 로드합니다. 편리하지만 충돌 위험이 있으므로 드물게 사용하세요. 이름 있는 네임스페이스가 더 안전하고 코드를 읽을 때 각 멤버의 출처를 명확히 보여줍니다.
// _variables.scss
$primary: blue;
$secondary: green;
// Rename the namespace with 'as'
@use 'variables' as v;
.btn {
background: v.$primary;
color: v.$secondary;
}
// Or remove the namespace entirely (use with caution)
@use 'variables' as *;
.card {
background: $primary; // direct access, no prefix
}
// 'as *' can cause collisions - prefer named namespaces설정과 함께 쓰는 @use(with)
'with (...)'는 로드 시 모듈의 !default 변수를 설정합니다. @import의 전역 변수 설정 패턴을 대체합니다. with 절은 모듈을 다른 방식으로 사용하기 전에 와야 합니다. 라이브러리 테마와 디자인 토큰을 설정하는 표준 방법입니다.
// _theme.scss
$primary: blue !default;
$radius: 4px !default;
.button {
background: $primary;
border-radius: $radius;
}
// main.scss - configure variables on import
@use 'theme' with (
$primary: red,
$radius: 8px
);
// The 'with' clause sets variables marked !default
// This is how libraries are configured by users@use와 @import 비교
@import에서 @use로 마이그레이션: 멤버는 네임스페이스화되고, 파일은 한 번 로드되며, -나 _로 시작하는 멤버는 비공개(노출되지 않음)가 됩니다. @use는 의존성을 명시적이고 실수로 인한 전역 오염을 막습니다. 큰 코드베이스 마이그레이션에는 sass-migrator 도구를 사용하세요.
// @import (old) - global, no namespace
@import 'variables';
.button { background: $primary; } // global $primary
// @use (new) - namespaced, loaded once
@use 'variables';
.button { background: variables.$primary; }
// Key differences:
// @import: global scope, runs multiple times, no privacy
// @use: namespaced, runs once, supports private (-prefix)
// _mixins.scss with a private member
@mixin -internal { /* private - not exposed */ }
@mixin public { @include -internal; }
// @use only exposes non-private (no dash prefix) members믹스인(@mixin / @include)
믹스인 정의와 사용
@mixin은 재사용 가능한 선언 블록(규칙도 포함)을 정의합니다. @include는 사용된 위치에 믹스인 내용을 삽입합니다. 믹스인은 벤더 접두사, clearfix, 반복 선언 그룹에 이상적입니다. @extend와 달리 믹스인은 포함할 때마다 선언을 복제합니다.
// Define a mixin with @mixin
@mixin center {
display: flex;
justify-content: center;
align-items: center;
}
@mixin card-shadow {
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
// Use with @include
.hero {
@include center;
height: 200px;
}
.modal {
@include center;
@include card-shadow;
}믹스인 인자
믹스인은 함수처럼 인자를 받습니다. 위치로 전달(순서 중요)하거나 이름으로 전달(순서 무관, 더 명확)할 수 있습니다. 이름 인자는 선택적 매개변수가 많은 믹스인에 유용합니다. 인자는 믹스인을 다양한 값에서 유연하고 재사용 가능하게 만듭니다.
@mixin button($bg, $color) {
background: $bg;
color: $color;
padding: 8px 16px;
border: none;
border-radius: 4px;
}
// Pass arguments by position
.btn-primary { @include button(blue, white); }
.btn-danger { @include button(red, white); }
// Pass arguments by name (clearer, order-independent)
.btn-info { @include button($color: white, $bg: teal); }기본 인자
기본 인자 값은 믹스인을 유연하게 만듭니다. 호출자는 인자를 생략해 기본값을 쓸 수 있습니다. 이름 인자로 특정 매개변수만 덮어쓰고 나머지는 기본값으로 둘 수 있습니다. 기본값은 정의 시 한 번이 아니라 믹스인을 포함할 때마다 평가됩니다.
@mixin border($width: 1px, $style: solid, $color: #ccc) {
border: $width $style $color;
}
// Use all defaults
.box { @include border; }
// border: 1px solid #ccc;
// Override one - use named args to skip earlier ones
.card { @include border($color: blue); }
// border: 1px solid blue;
// Override by position
.banner { @include border(2px, dashed); }
// border: 2px dashed #ccc;@content가 있는 믹스인
@content는 @include에 전달된 스타일 블록을 주입합니다. 미디어 쿼리 믹스인, 키프레임, 래퍼 문맥에 매우 강력합니다. 포함된 블록은 호출 범위에서 평가되므로 호출자의 변수를 사용할 수 있습니다. 인자 전달은 @content 섹션을 참고하세요.
// @content lets you pass a block of styles to a mixin
@mixin respond-to($breakpoint) {
@media (min-width: $breakpoint) {
@content; // injected styles go here
}
}
.sidebar {
width: 100%;
@include respond-to(768px) {
width: 250px; // this block replaces @content
float: left;
}
}
// Compiles to:
// .sidebar { width: 100%; }
// @media (min-width: 768px) { .sidebar { width: 250px; float: left; } }가변 인자(...)
... 연산자는 두 가지 용도가 있습니다. 믹스인 정의에서는 추가 인자를 리스트로 모으고(가변 인자), 호출 지점에서는 리스트를 개별 인자로 펼칩니다. box-shadow나 transition처럼 가변 개수의 값을 받는 CSS 속성을 감싸는 믹스인에 필수입니다.
// ... captures multiple args into a list (or expands a list)
@mixin box-shadow($shadows...) {
box-shadow: $shadows;
}
.card { @include box-shadow(0 1px 2px black, 0 4px 8px gray); }
// box-shadow: 0 1px 2px black, 0 4px 8px gray;
// Expanding a list into arguments
$shadows: 0 1px 2px black, 0 4px 8px gray;
.modal { @include box-shadow($shadows...); }
// Also works for @include with maps as keyword args
@mixin theme($colors) { /* ... */ }
@include theme(("bg": red, "fg": white)...);@extend와 상속
기본 @extend
@extend는 한 선택자가 다른 선택자의 모든 스타일을 상속하게 하며, 규칙을 복제하지 않고 공유합니다. 컴파일된 CSS는 선택자를 함께 묶습니다. 공통 기본 스타일에는 믹스인보다 DRY하지만 예상치 못한 선택자 체인을 만들 수 있으므로 주의해서 사용하세요.
.message {
padding: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
// .success inherits all .message styles
.success {
@extend .message;
background: #d4edda;
border-color: #c3e6cb;
}
.error {
@extend .message;
background: #f8d7da;
border-color: #f5c6cb;
}
// Compiles to: .message, .success, .error { padding: 10px; ... }복합 선택자 확장
@extend는 클래스, 요소 선택자, 의사 클래스, 복합 선택자 등 모든 선택자와 동작합니다. .icon.large를 확장하면 .icon과 .icon.large 모두에 맞는 규칙을 상속합니다. 복합 선택자 확장은 생성된 CSS가 예상 밖으로 캐스케이드되고 출력이 비대해질 수 있으니 주의하세요.
// You can extend any selector, not just classes
a:hover {
text-decoration: underline;
}
.link-card:hover {
@extend a:hover; // inherits :hover rule
color: blue;
}
// Extending with compound selectors
.icon {
display: inline-block;
}
.icon.large {
font-size: 24px;
}
.icon-x { @extend .icon.large; } // extends BOTH rules@extend 체이닝
@extend 체인: B가 A를 확장하고 C가 B를 확장하면 C는 둘 다 상속합니다. 컴파일된 CSS는 그에 따라 선택자를 묶습니다. 깊은 체인은 큰 선택자 목록과 예상 밖의 명시도를 만들 수 있습니다. 대부분의 재사용 상황에서는 체인된 @extend보다 믹스인이 더 예측 가능합니다.
.base {
display: block;
padding: 8px;
}
.intermediate {
@extend .base;
background: #eee;
}
.final {
@extend .intermediate;
color: red;
}
// .final inherits from .intermediate which inherits from .base
// Compiles to: .base, .intermediate, .final { display: block; padding: 8px; }
// .intermediate, .final { background: #eee; }
// .final { color: red; }@extend !optional
@extend에 !optional을 붙이면 대상 선택자가 없을 때 오류를 내지 않고 확장을 조용히 건너뜁니다. 선택적이거나 조건부로 로드되는 선택자를 확장할 때 유용합니다. !optional이 없으면 대상이 없을 때 @extend가 컴파일을 실패시킵니다.
// !optional prevents errors if the selector doesn't exist
.fluent {
@extend .nonexistent !optional; // no error, just skipped
color: blue;
}
// Without !optional, extending a missing selector throws:
// ".nonexistent failed to @extend"
// Use !optional when the extension target may or may not exist
// (e.g., optional theme classes from a third-party library)@extend와 @include 믹스인
@extend는 선택자를 묶어(많이 재사용하면 CSS가 작아짐) 숨은 결합을 만듭니다. @include 믹스인은 선언을 복제해(CSS가 커짐) 자기 완결적이고 설정 가능합니다. 새 코드에는 예측 가능한 믹스인을 권장하세요. @extend는 주로 한 파일 안의 의미적 관계에 사용하세요.
// @extend - shares one rule, groups selectors
.btn { padding: 8px; }
.primary { @extend .btn; background: blue; }
// -> .btn, .primary { padding: 8px; }
// @mixin - duplicates declarations each use
@mixin btn { padding: 8px; }
.primary { @include btn; background: blue; }
// -> .primary { padding: 8px; background: blue; }
// When to use which:
// @extend: share base styles semantically (DRY selectors)
// @mixin: configurable repeated declarations (with args)
// Avoid @extend across module boundaries (can cause side effects)플레이스홀더 선택자(%placeholder)
%placeholder 기초
%placeholder 선택자(예: %base-message)는 확장되기 위해서만 존재하는 규칙이라 단독으로는 CSS에 출력되지 않습니다. 실제 클래스에 @extend할 때 생기는 미사용 기본 클래스 문제를 피할 수 있습니다. 순전히 상속용 스타일을 공유하는 가장 깔끔한 방법입니다.
// %placeholder selectors are NOT output in CSS
// They only appear when @extended
%base-message {
padding: 10px;
border-radius: 4px;
}
.success { @extend %base-message; background: green; }
.error { @extend %base-message; background: red; }
// Compiles to (notice %base-message is gone):
// .success, .error { padding: 10px; border-radius: 4px; }
// .success { background: green; }
// .error { background: red; }플레이스홀더와 클래스
실제 클래스를 @extend하면 HTML에서 한 번도 쓰지 않아도 그 클래스가 출력에 나타납니다. 플레이스홀더는 이를 해결합니다. %base는 확장된 곳에서만 출력됩니다. 기본이 HTML에서 직접 쓰이면 실제 클래스를, 순전히 상속용이면 플레이스홀더를 사용하세요.
// Class as extend target - the class IS output
.message { padding: 10px; } // appears in CSS even if unused
.success { @extend .message; }
// Placeholder as extend target - NOT output
%message { padding: 10px; } // never appears in CSS
.success { @extend %message; }
// Result is identical for .success, but the placeholder
// version doesn't pollute the CSS with an unused .message rule.
// Use placeholders for internal/inheritance-only base styles.@extend와 플레이스홀더
한 선택자가 여러 플레이스홀더를 @extend해 공유 스타일 집합을 결합할 수 있습니다. 미사용 기본 클래스를 출력하지 않고 재사용 가능한 빌딩 블록을 구성합니다. 플레이스홀더는 여러 구체적 컴포넌트가 공유하는 디자인 시스템 기본 요소(카드, 버튼, 입력)에 빛납니다.
%card-base {
background: white;
border: 1px solid #eee;
border-radius: 8px;
padding: 16px;
}
%card-shadow {
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}
// Combine multiple placeholders
.featured-card {
@extend %card-base;
@extend %card-shadow;
border-color: gold;
}여러 플레이스홀더 공유
여러 선택자가 같은 플레이스홀더를 @extend하면 Sass가 출력에서 이들을 묶어 간결한 CSS를 만듭니다. Sass에서 가장 효율적인 스타일 공유 형태입니다. 플레이스홀더는 런타임 CSS 클래스 비대 없이 상속/합성을 가능하게 합니다.
%button { padding: 8px 16px; border: none; cursor: pointer; }
%rounded { border-radius: 4px; }
%shadow { box-shadow: 0 1px 3px rgba(0,0,0,0.2); }
// Many components share the same placeholders
.btn-primary { @extend %button; @extend %rounded; @extend %shadow; background: blue; }
.btn-secondary { @extend %button; @extend %rounded; background: gray; }
.btn-ghost { @extend %button; background: transparent; }
// Sass deduplicates: %button's rule is shared across all three플레이스홀더 사용 사례
플레이스홀더는 재사용 유틸리티 패턴에 이상적입니다: 중앙 정렬, clearfix, 접근성(visually-hidden), 디자인 시스템 기본 요소. 패턴을 한곳에 모으고 사용되지 않으면 출력하지 않습니다. 설정 불가능한 유틸리티 스타일을 공유하는 깔끔한 방법입니다.
// 1. Design system primitives
%abs-center {
position: absolute;
top: 50%; left: 50%;
transform: translate(-50%, -50%);
}
// 2. Clearfix
%clearfix::after {
content: "";
display: table;
clear: both;
}
// 3. Visually hidden (accessibility)
%visually-hidden {
position: absolute;
width: 1px; height: 1px;
overflow: hidden;
clip: rect(0 0 0 0);
}
.modal { @extend %abs-center; }
.container { @extend %clearfix; }
.sr-only { @extend %visually-hidden; }함수(@function)
함수 정의
@function은 값을 @return하는 재사용 가능한 계산을 정의합니다. 함수는 속성 값에서 호출됩니다(선언을 출력하는 믹스인과 다름). 단위 변환, 색상 계산, 반응형 스케일링 같은 계산에 사용하세요. 반환 값은 모든 Sass 데이터 타입이 될 수 있습니다.
// @function defines a function that returns a value
@function rem($px) {
$base: 16px;
@return ($px / $base) * 1rem;
}
// Use it like a CSS function
body { font-size: rem(16); } // 1rem
h1 { font-size: rem(32); } // 2rem
.small { font-size: rem(12); } // 0.75rem
// Functions return values; mixins output CSS rules함수 인자와 기본값
함수는 믹스인처럼 기본 인자, 이름 인자, 가변 인자(...)를 지원합니다. 기본값은 함수 호출을 편리하게 만듭니다. 이름 인자는 선택적 매개변수가 많은 함수의 가독성을 높입니다. 가변 인자는 함수가 임의 개수의 값을 받게 합니다.
@function spacing($factor: 1, $base: 8px) {
@return $base * $factor;
}
// Use defaults
.card { padding: spacing(); } // 8px
.card-lg { padding: spacing(2); } // 16px
// Override by name
.section { padding: spacing($base: 10px); } // 10px
.hero { padding: spacing(3, 10px); } // 30px
// Variable arguments work too
@function max-of($nums...) {
@return ...; // implement with reduce
}내장 함수 개요
Sass는 색상, 수학, 문자열, 리스트, 맵을 위한 풍부한 내장 함수를 제공합니다. 최신 Sass는 이를 모듈(sass:math, sass:color, sass:string, sass:list, sass:map, sass:meta)로 구성하며 @use로 로드합니다. 전역 함수 이름도 동작하지만 네임스페이스 모듈 함수 사용이 권장됩니다.
// Color functions
lighten(#000, 50%) // gray
rgba(#fff, 0.5) // semi-transparent white
mix(red, blue) // purple
// Math functions
percentage(0.5) // 50%
round(3.6) // 4
min(10px, 20px) // 10px
// String functions
to-upper-case("abc") // "ABC"
str-length("hello") // 5
// List/Map functions
length(1 2 3) // 3
map-get(("a": 1), "a") // 1
// Modern Sass uses modules: @use 'sass:math'; math.div(10, 2)실용 함수 예제
함수는 재사용 가능한 계산을 캡슐화하는 데 탁월합니다: 단위 변환(px/em/rem), 맵을 통한 z-index 관리, 디자인 토큰 조회. 이를 함수에 중앙화하면 일관성이 보장되고 기본 글꼴 크기 변경 같은 수정이 모든 곳에 자동 전파됩니다.
// Convert px to em relative to a context
@function em($px, $context: 16px) {
@return ($px / $context) * 1em;
}
// Generate a z-index from a scale map
$z-indexes: (
"base": 0,
"dropdown": 100,
"modal": 200,
"toast": 300,
);
@function z($name) {
@return map-get($z-indexes, $name);
}
// Usage
body { font-size: em(18px); } // 1.125em
.modal { z-index: z("modal"); } // 200
.toast { z-index: z("toast"); } // 300재귀 함수
Sass 함수는 @if 조건문과 자기 호출로 재귀를 지원합니다. 팩토리얼, 피보나치 같은 계산 시퀀스를 만들 수 있습니다. 하지만 Sass 재귀는 꼬리 호출 최적화가 없고 느리므로 실제 스타일시트에서 깊은 재귀는 피하세요. 반복 계산에는 @for 루프를 권장합니다.
// Functions can call themselves (recursion)
@function factorial($n) {
@if $n <= 1 {
@return 1;
} @else {
@return $n * factorial($n - 1);
}
}
.power { width: factorial(5) * 1px; } // 120px
// Fibonacci
@function fib($n) {
@if $n < 2 { @return $n; }
@return fib($n - 1) + fib($n - 2);
}
// Note: deep recursion is slow in Sass - use sparingly제어 지시문
@if / @else if / @else
@if/@else if/@else는 비교 결과에 따라 조건부로 스타일을 출력합니다. Sass는 동등 비교에 ==와 !=를 사용합니다(=== 아님). 불리언 연산자는 'and', 'or', 'not'입니다(&&, ||, ! 아님). 테마 전환, 기능 플래그, 믹스인/함수 내 반응형 로직에 유용합니다.
@mixin theme($mode) {
@if $mode == dark {
background: #222;
color: #eee;
} @else if $mode == light {
background: #fff;
color: #333;
} @else {
background: gray;
color: black;
}
}
.dark { @include theme(dark); }
.light { @include theme(light); }
.auto { @include theme(auto); }
// Comparison operators: ==, !=, <, >, <=, >=, and, or, not@for 루프
@for는 변수를 시작 값에서 끝 값까지 반복합니다. 'through'는 끝 값을 포함하고, 'to'는 끝 값을 제외합니다. 그리드 열, 순차 애니메이션, 번호가 붙은 유틸리티 클래스 생성에 흔합니다. #{} 보간으로 카운터를 선택자에 삽입하세요.
// @for $var from <start> through <end> (inclusive)
@for $i from 1 through 3 {
.col-#{$i} { width: 100% / $i; }
}
// .col-1 { width: 100%; } .col-2 { width: 50%; } .col-3 { width: 33.333%; }
// 'to' is EXCLUSIVE (excludes the end)
@for $i from 1 to 3 {
.item-#{$i} { order: $i; }
}
// .item-1, .item-2 (no .item-3)
// Use 'through' for inclusive, 'to' for exclusive ranges@each 루프(리스트)
@each는 리스트를 반복하며 각 항목을 변수에 바인딩합니다. 설정 리스트에서 테마 변형, 아이콘 클래스, 유틸리티 클래스를 생성하는 데 이상적입니다. 리스트의 리스트는 반복마다 여러 변수로 풀어 (name, color) 튜플 같은 쌍 데이터를 처리할 수 있습니다.
// Iterate over a list
$icons: user, home, settings, search;
@each $name in $icons {
.icon-#{$name} {
background-image: url("/icons/#{$name}.svg");
}
}
// .icon-user, .icon-home, .icon-settings, .icon-search
// Multiple values (unpacking)
@each $name, $color in (success green), (error red) {
.alert-#{$name} { color: $color; }
}맵과 @each
맵에 @each를 쓰면 반복마다 키와 값이 모두 바인딩됩니다. 설정 맵에서 반응형 유틸리티, 테마 변형, 브레이크포인트 인식 클래스를 생성하는 표준 방법입니다. 최신 Sass에서 맵 반복 순서는 삽입 순서를 따릅니다.
$breakpoints: (
"sm": 576px,
"md": 768px,
"lg": 1024px,
"xl": 1280px,
);
// Iterate key-value pairs of a map
@each $name, $size in $breakpoints {
.container-#{$name} {
max-width: $size;
margin: 0 auto;
}
}
// .container-sm, .container-md, .container-lg, .container-xl
// Also destructuring lists of maps for richer config
$buttons: (("primary", blue), ("danger", red));@while 루프
@while은 조건이 거짓이 될 때까지 반복하며 카운터를 직접 갱신해야 합니다. @for가 맞지 않는 비선형 진행(예: 매 단계 두 배)에 사용하세요. 루프가 반드시 종료되게 하세요. 증가를 잊으면 컴파일이 멈추는 무한 루프가 됩니다.
// @while repeats while a condition is true
$i: 1;
@while $i <= 5 {
.mt-#{$i} { margin-top: $i * 4px; }
$i: $i + 1;
}
// .mt-1 { margin-top: 4px; } ... .mt-5 { margin-top: 20px; }
// Unlike @for, you control the increment
// WARNING: always increment/decrement to avoid infinite loops!
$i: 6;
@while $i > 0 {
.delay-#{$i} { transition-delay: $i * 100ms; }
$i: $i - 1;
}리스트와 맵
리스트
리스트는 Sass의 배열 타입이며 공백이나 쉼표로 구분합니다. 인덱스는 대부분의 언어와 달리 1부터 시작합니다. nth($list, 1)은 첫 항목을 반환합니다. 음수 인덱스는 끝에서부터 셉니다. 단일 값은 요소 하나짜리 리스트로 취급됩니다. 리스트는 중첩될 수 있습니다.
// Lists are ordered collections (like arrays)
// Separated by spaces or commas
$sizes: 10px 20px 30px; // space-separated
$colors: red, green, blue; // comma-separated
$mixed: (1px 2px) (3px 4px); // nested lists
// Single value is also a list of length 1
$one: 5px;
// Indexes are 1-based!
$list: a b c;
nth($list, 1); // a (NOT 0-indexed)
nth($list, -1); // c (negative = from end)
length($list); // 3리스트 함수
리스트 함수: 접근에는 length(), nth(), index(); append(), join(), insert-nth()는 새 리스트를 반환합니다(리스트는 불변). zip()은 여러 리스트의 요소를 쌍으로 묶습니다. separator()는 리스트의 구분자 를 반환합니다. 반복에는 @each를 사용하세요. 최신 API는 sass:list 모듈에 있습니다.
$list: a b c;
// Access
length($list); // 3
nth($list, 2); // b
index($list, b); // 2 (position of b, or null)
// Modify (return NEW list - lists are immutable)
append($list, d); // a b c d
join(a b, c d); // a b c d
join((a b), (c d), comma); // a, b, c, d
// Insert
insert-nth($list, 2, x); // a x b c
// Misc
zip(1 2, a b); // (1 a) (2 b) - pairs elements맵
맵은 키-값 컬렉션(연관 배열)입니다. 키는 고유해야 하고 값은 중첩 맵을 포함한 모든 Sass 타입이 될 수 있습니다. 값을 읽으려면 map-get(), 존재 여부는 map-has-key()를 사용하세요. 맵은 디자인 토큰, 브레이크포인트, 테마 팔레트를 모델링하는 표준 방법입니다.
// Maps are key-value pairs (like objects/dictionaries)
$colors: (
"primary": #3498db,
"secondary": #2ecc71,
"danger": #e74c3c,
"warning": #f39c12,
);
// Access values
map-get($colors, "primary"); // #3498db
// Check existence
map-has-key($colors, "success"); // false
// Keys must be unique; values can be any type (even nested maps)
$breakpoints: (
"mobile": (max: 767px),
"desktop": (min: 768px),
);맵 함수
맵 함수: map-get()은 값을 읽고, map-keys()/map-values()는 리스트를 반환하며, map-merge()는 맵을 결합하고(테마 확장에 유용), map-remove()는 키를 삭제합니다. 맵은 불변이라 함수가 새 맵을 반환합니다. 최신 API는 sass:map 모듈 아래에 네임스페이스화되어 있습니다.
$colors: ("a": 1, "b": 2);
// Access
map-get($colors, "a"); // 1
map-has-key($colors, "c"); // false
// Keys & values as lists
map-keys($colors); // ("a", "b")
map-values($colors); // (1, 2)
// Merge (combines two maps; second wins on conflicts)
$base: ("x": 1, "y": 2);
$override: ("y": 99, "z": 3);
map-merge($base, $override); // ("x": 1, "y": 99, "z": 3)
// Remove keys
map-remove($colors, "a"); // ("b": 2)반복과 구조 분해
@each는 맵(키, 값)과 리스트의 리스트를 구조 분해해 반복마다 여러 변수를 바인딩합니다. 설정 데이터를 생성 CSS로 바꾸는 디자인 시스템의 강력한 패턴입니다. 맵과 결합하면 하나의 설정 맵으로 유틸리티 클래스 프레임워크 전체를 구동할 수 있습니다.
$grid: (
"sm": 576px,
"md": 768px,
"lg": 1024px,
);
// @each destructures map into key+value
@each $name, $size in $grid {
@media (min-width: $size) {
.container-#{$name} { max-width: $size; }
}
}
// Nested destructuring with lists of lists
$config: (("primary", blue, white), ("danger", red, white));
@each $name, $bg, $fg in $config {
.btn-#{$name} { background: $bg; color: $fg; }
}색상 함수
lighten / darken
lighten()과 darken()은 색상의 명도를 백분율만큼 이동합니다. 어떤 채널이 바뀌는지 명시적인 sass:color의 color.adjust() 사용이 권장되어 폐기되었습니다. 이미 극단적인 색상에 순수 lighten/darken을 쓰면 예상 밖 결과가 나올 수 있으므로 HSL 기반 조정을 권장합니다.
$base: #3498db;
.light { background: lighten($base, 20%); } // lighter blue
.dark { background: darken($base, 20%); } // darker blue
// Note: lighten/darken are deprecated in modern Sass
// Prefer sass:color adjust() for clarity:
@use 'sass:color';
.adjusted {
// same effect, explicit
background: color.adjust($base, $lightness: 20%);
border-color: color.adjust($base, $lightness: -20%);
}rgba / rgb / 투명도
rgba($color, $alpha)는 모든 색상에 투명도를 추가하는 가장 흔한 색상 함수입니다. rgba()는 숫자 인자 4개도 받습니다. 최신 sass:color 모듈은 명시적 알파 제어를 위해 color.adjust($alpha: ...)를 제공합니다. CSS Color 4 공간 문법(rgb(r g b / a%))도 최신 Sass에서 유효합니다.
$brand: #3498db;
// Add alpha to any color
.semi { background: rgba($brand, 0.5); } // #3498db at 50%
.fade { background: rgba($brand, 0.1); } // very transparent
// rgba() also accepts 4 numeric args
.box { background: rgba(52, 152, 219, 0.8); }
// Modern alternative: color.adjust for alpha
@use 'sass:color';
.glass { background: color.adjust($brand, $alpha: -0.5); }
// rgb() and rgba() with space syntax (CSS Color 4)
.modern { background: rgb(52 152 219 / 80%); }mix / 색상 혼합
mix($color1, $color2, $weight)는 두 색상을 혼합하며 $weight는 $color1의 백분율입니다(기본 50%). 틴트에는 mix($color, white), 셰이드에는 mix($color, black)를 쓰면 lighten()/darken()보다 자연스러운 경우가 많습니다. color.mix는 최신 네임스페이스 대응 함수입니다.
// mix() blends two colors by a weight (default 50%)
$mix: mix(red, blue); // purple (50/50)
$mix30: mix(red, blue, 30%); // 30% red, 70% blue (bluer)
// Useful for generating tints and shades
$base: #3498db;
.tint { background: mix($base, white, 20%); } // 20% blue, 80% white
.shade { background: mix($base, black, 20%); } // 20% blue, 80% black
// sass:color module
@use 'sass:color';
.blended { background: color.mix(red, blue, 50%); }adjust-color / scale-color / change-color
세 가지 정밀 색상 도구: color.adjust()는 채널에 델타를 더하고, color.scale()은 채널을 백분율로 최소/최대 방향으로 스케일합니다(안전하며 초과하지 않음), color.change()는 채널을 절대값으로 설정합니다. 전역 adjust-color/scale-color/change-color는 폐기된 별칭입니다.
@use 'sass:color';
$base: #3498db;
// adjust: ADDS to channels (absolute change)
.a { background: color.adjust($base, $red: 30, $alpha: -0.3); }
// scale: SCALES channels by % (relative change, stays in range)
.s { background: color.scale($base, $lightness: 50%); }
// change: SETS channels to exact values (replaces)
.c { background: color.change($base, $lightness: 50%, $hue: 0); }
// adjust moves by a delta, scale shrinks/grows toward min/max,
// change overwrites with a fixed value.hue / saturation / complement
color.hue/saturation/lightness는 HSL 채널을 읽으므로 조건 로직에 유용합니다. color.complement()는 반대 색상(강조색에 유용), color.grayscale()은 채도를 낮추고, color.invert()는 RGB 반전을 합니다. color.hsl()은 HSL 값으로 색상을 만듭니다. 프로그래밍 방식 팔레트 생성을 가능하게 합니다.
@use 'sass:color';
$c: #3498db;
// Read HSL channels
color.hue($c); // 204deg
color.saturation($c); // 70%
color.lightness($c); // 53%
// Derive new colors
.complement { background: color.complement($c); } // opposite hue
.grayscale { background: color.grayscale($c); } // desaturated
.invert { background: color.invert($c); } // RGB inverse
// Build from HSL
.from-hsl { background: color.hsl(204, 70%, 53%); }수학 연산
기본 산술
Sass는 숫자에 +, -, *, /, %를 지원하고 단위를 처리합니다. CSS는 구분자로 /를 사용하므로(font: 16px/1.5) 나눗셈으로서의 순수 /는 폐기되었습니다. sass:math의 math.div()나 괄호를 사용하세요. +와 -는 단위가 호환되어야 합니다. 단위가 있는 두 값을 곱하는 것은 보통 오류입니다.
$base: 16px;
// Sass does math on numbers (with unit handling)
width: 100% - 20px; // ERROR - incompatible units
width: 100px + 20px; // 120px
width: 100px * 2; // 200px
width: 100px / 2; // 50px (use math.div in modern Sass)
width: (100px / 2); // 50px (parenthesized = math, not CSS)
// Modern division (the / operator is deprecated for division)
@use 'sass:math';
width: math.div(100px, 2); // 50px
width: math.div(100, 3); // 33.333...단위 변환
Sass는 물리 단위(px, in, cm, mm, pt, pc) 간에는 자동 변환하지만 px/em/rem/% 간에는 변환하지 않습니다. 변환 함수를 직접 작성해야 합니다. 흔한 패턴은 기본 글꼴 크기로 나누는 rem($px) 함수입니다. 단위 변환을 중앙화해 프로젝트의 간격 스케일을 일관되게 유지하세요.
$base-font: 16px;
// Convert px to rem
@function rem($px) {
@return math.div($px, $base-font) * 1rem;
}
h1 { font-size: rem(32px); } // 2rem
// Convert px to em (relative to context)
@function em($px, $context: 16px) {
@return math.div($px, $context) * 1em;
}
// Sass does NOT auto-convert between px/em/rem/%
// You must compute the ratio yourself.
// 1in = 96px, 1cm = 37.8px, 1pt = 1.33px (these DO auto-convert)수학 함수
sass:math는 round(), ceil(), floor(), abs(), min(), max(), percentage()와 (최신) 삼각/거듭제곱 함수, math.$pi 같은 상수를 제공합니다. 여기의 min()/max()는 Sass 함수이므로 실제 CSS min/max와 다릅니다(실제 CSS에는 따옴표 없는 CSS 함수 사용). 항상 math를 명시적으로 가져오세요.
@use 'sass:math';
// Rounding
math.round(3.6); // 4
math.ceil(3.1); // 4
math.floor(3.9); // 3
// Absolute & bounds
math.abs(-5); // 5
math.min(10px, 20px); // 10px
math.max(10px, 20px); // 20px
// Percentage conversion
math.percentage(0.5); // 50% (math.percentage, or global percentage)
// Trig & constants (Sass 1.65+)
math.sin(math.$pi); // ~0
math.cos(0); // 1
math.sqrt(16); // 4나머지와 나눗셈
math.div()는 최신 나눗셈 함수입니다. / 연산자는 CSS 리스트 구분자용으로 예약되어 있습니다(font: 16px/1.5). math.mod()는 나머지를 반환합니다. math.compatible()은 두 숫자를 더할 수 있는지 확인합니다. 산술에는 항상 @use 'sass:math'를 사용하세요. 나눗셈용 전역 /는 폐기되었고 제거될 예정입니다.
@use 'sass:math';
// Modulo (remainder)
math.unit(10px); // px
math.compatible(10px, 5px); // true (can add)
math.is-unitless(5); // true
// Division MUST use math.div (the / operator is for lists/CSS)
$result: math.div(100, 3); // 33.333...
// Modulo
$rem: math.mod(10, 3); // 1
// Generating a grid with modulo
@for $i from 1 through 12 {
.col-#{$i} { width: math.div($i, 12) * 100%; }
}비교와 논리 연산자
Sass는 동등 비교에 ==와 !=를 사용합니다. 불리언 연산자는 'and', 'or', 'not' 키워드이며 C 스타일 &&/||/!가 아닙니다. 우선순위를 명확히 하려면 괄호를 사용하세요. 이 연산자는 믹스인, 함수, 제어 지시문의 @if 조건을 구동합니다. 참 같은 값은 false와 null을 제외한 모든 값입니다.
// Comparison: ==, !=, <, >, <=, >=
@if $width > 100px { /* ... */ }
@if $count == 3 { /* ... */ }
@if $mode != "dark" { /* ... */ }
// Boolean logic: and, or, not (NOT &&, ||, !)
$enabled: true;
$mobile: false;
@if $enabled and not $mobile {
.desktop-only { display: block; }
}
@if $mode == "dark" or $mode == "night" {
background: black;
}
// Use parentheses to group
@if ($a > 1 and $b < 10) or $c == 5 { /* ... */ }문자열 함수
quote / unquote
quote()는 문자열을 따옴표로 감싸고 unquote()는 제거합니다. Sass는 따옴표 문자열(content, 글꼴 이름에 사용)과 따옴표 없는 문자열(식별자, 클래스 이름에 사용)을 구분합니다. 많은 함수가 둘 다 받지만 출력 서식과 선택자 생성에는 구분이 중요합니다.
// quote() forces quotes around a string
$unquoted: Helvetica;
$quoted: quote($unquoted); // "Helvetica"
// unquote() removes quotes
$quoted: "Arial";
$plain: unquote($quoted); // Arial
// Useful when a string needs to be quoted for output
.url { background: url(quote("/img/x.png")); }
// url("/img/x.png")
// Quoted vs unquoted matters for some CSS values
// Class names and property names are usually unquoted대소문자 함수
to-upper-case()와 to-lower-case()는 문자열 대소문자를 변환하므로 일관된 클래스 이름, content 값 생성이나 입력 정규화에 유용합니다. #{} 보간과 결합하면 변수에서 동적 선택자와 content를 만들 수 있습니다. 최신 네임스페이스 버전 은 sass:string에 있습니다.
// Change string case
$upper: to-upper-case("hello"); // "HELLO"
$lower: to-lower-case("WORLD"); // "world"
// Practical: generate uppercase class names
$states: success, warning, error;
@each $s in $states {
.badge-#{to-upper-case($s)} {
content: "#{to-upper-case($s)}";
}
}
// .badge-SUCCESS { content: "SUCCESS"; } etc.str-length / str-slice / str-index
sass:string 함수: string.length()는 문자 수, string.slice($str, $start, $end)는 부분 문자열(1부터 시작, 음수는 끝에서), string.index()는 부분 문자열 위치(1부터 시작, 없으면 null)를 반환합니다. Sass에는 내장 split이 없으므로 index()와 slice()를 쓰는 루프로 구현하세요.
@use 'sass:string';
$str: "Hello, World";
// Length (character count)
string.length($str); // 12
// Slice (substring) - 1-based, supports negatives
string.slice($str, 1, 5); // "Hello"
string.slice($str, 8); // "World"
string.slice($str, -5); // "World" (from end)
// Index of substring (1-based, or null if not found)
string.index($str, "World"); // 8
string.index($str, "xyz"); // null
// Split is not built-in - use a custom function with index+slicestr-insert / str-replace
string.insert($string, $insert, $position)는 1부터 시작하는 위치에 부분 문자열을 삽입합니다(끝에 붙이려면 큰 수 사용). string.replace($string, $to-replace, $replace-with, $limit?)는 부분 문자열을 교체합니다(기본 전체 또는 개수 제한). 프로그래밍 방식 클래스 이름과 content 생성에 필수입니다.
@use 'sass:string';
// str-insert: insert at position (1-based)
string.insert("Hello", "!", 6); // "Hello!"
string.insert("World", "Hello ", 1); // "Hello World"
// Modern Sass (1.55+) has string.replace
string.replace("a-b-c", "-", "_"); // "a_b_c" (replace all)
string.replace("a-b-c", "-", "_", 1); // "a_b-c" (limit 1)
// Build dynamic strings
$prefix: "icon";
$name: string.insert($prefix, "-user", 100); // "icon-user"문자열 보간 패턴
#{} 보간은 모든 Sass 값(숫자, 리스트, 색상, 불리언)을 문자열 표현으로 변환해 삽입합니다. 동적 선택자, 속성 이름, content 값, URL을 만드는 데 사용하세요. 보간은 Sass 값과 일반 변수가 허용되지 않는 CSS 텍스트 출력 사이의 다리입니다.
$prefix: "btn";
$modifier: "primary";
// #{} converts any value to a string and embeds it
.#{$prefix}-#{$modifier} { /* ... */ } // .btn-primary
// Interpolating numbers, lists, booleans
$count: 3;
.item-#{$count} { order: $count; } // .item-3 { order: 3; }
// Interpolating in @include and @media
@mixin respond-to($bp) {
@media (max-width: $bp) { @content; }
}
// Interpolating function calls
.content::after {
content: "#{to-upper-case('hello')}";
}@at-root
기본 @at-root
@at-root는 현재 중첩 문맥을 빠져나와 중첩된 규칙을 스타일시트 최상위에 출력합니다. @at-root가 없으면 .parent 안의 .child는 .parent .child(하위)로 컴파일됩니다. @at-root를 쓰면 .child만 됩니다. 관련 규칙을 소스에서 묶어 두면서 평탄한 선택자를 출력할 수 있습니다.
.parent {
color: blue;
// @at-root jumps out of the nesting
@at-root .child {
color: red;
}
}
// Compiles to (note: .child is NOT nested under .parent):
// .parent { color: blue; }
// .child { color: red; } <- top-level, not .parent .child
// Useful for defining sibling/related rules inside a block
// without creating a descendant selector.선택자와 @at-root
@at-root를 &와 결합해 부모 선택자의 일부를 선택적으로 유지하세요. @at-root .wrapper &는 .component .wrapper가 아니라 .wrapper .component(문맥을 앞에 붙임)를 출력합니다. 테마/문맥 덮어쓰기를 컴포넌트 코드와 함께 두는 깔끔한 방법입니다.
.component {
width: 100px;
// Combine @at-root with & to keep part of the parent
@at-root .wrapper & {
background: yellow;
}
// -> .wrapper .component { background: yellow; }
// Useful for context overrides without deep nesting
@at-root .dark-theme & {
color: white;
}
// -> .dark-theme .component { color: white; }
}BEM을 위한 @at-root
@at-root는 BEM 수정자 클래스(.block--active)를 하위가 아니라 형제로 생성하도록 돕습니다. @at-root가 없으면 .block 안에 .block--active를 중첩해 .block .block--active가 되는데, 이는 블록 안의 활성 블록이라는 잘못된 의미입니다. @at-root는 수정자를 최상위에 출력하며 이것이 올바른 BEM 출력입니다.
.block {
// State classes as siblings, not descendants
@at-root {
.block--active { border-color: blue; }
.block--disabled { opacity: 0.5; }
}
// Or inline form
@at-root .block--hidden { display: none; }
}
// Compiles to top-level siblings:
// .block { ... }
// .block--active { border-color: blue; }
// .block--disabled { opacity: 0.5; }
// .block--hidden { display: none; }
// Avoids accidentally generating .block .block--active미디어 쿼리와 @at-root
@at-root (with: media)는 규칙을 선택자 중첩 밖으로 끌어올리되 @media 블록 안에는 유지합니다. @at-root (without: media)는 반대입니다. with/without 절은 어떤 문맥(rule, media, supports)을 보존할지 제어합니다. 고급 기능이지만 견고한 반응형 믹스인 라이브러리를 만드는 데 필수입니다.
.component {
width: 100%;
// @at-root lifts media queries to the top level
@at-root (with: media) {
@media (min-width: 768px) {
& { width: 50%; }
}
}
// -> @media (min-width: 768px) { .component { width: 50%; } }
}
// Default @at-root (without: rule) lifts OUT of everything
// @at-root (with: media) keeps the @media context but exits rules
// Useful in complex nested mixins to control scope precisely@at-root without (with)
(without: ...)와 (with: ...) 절은 @at-root가 빠져나갈 중첩 문맥을 제어합니다. 흔한 문맥: 'rule'(선택자), 'media'(@media), 'supports'(@supports), 'all'. (without: rule)은 @media는 유지하고 선택자는 빠져나갑니다. 이 정밀한 범위 제어로 고급 믹스인과 라이브러리 패턴을 만들 수 있습니다.
.parent {
@media (min-width: 768px) {
.child {
width: 50%;
// Exit only the rule, keep the @media
@at-root (without: rule) {
.sibling { width: 25%; }
}
// -> @media (min-width: 768px) { .sibling { width: 25%; } }
// Exit everything (default)
@at-root .top { color: red; }
// -> .top { color: red; } (no @media, no parent)
}
}
}@content
@content 기초
@mixin 안의 @content는 @include { ... }로 전달된 스타일 블록의 자리 표시자입니다. 포함된 블록이 호출 지점에서 @content를 대체합니다. 믹스인이 사용자 정의 스타일을 감쌀 수 있게 하며, 미디어 쿼리, 키프레임, 내부 내용이 사용처마다 달라지는 '래퍼' 패턴에 필수입니다.
// @content marks where the included block is injected
@mixin highlighted {
background: yellow;
font-weight: bold;
@content; // the block passed to @include goes here
}
.title {
@include highlighted {
color: red; // injected where @content was
font-size: 20px;
}
}
// Compiles to:
// .title { background: yellow; font-weight: bold; color: red; font-size: 20px; }인자가 있는 @content
@content ($args)는 믹스인에서 포함된 블록으로 값을 전달하며, 블록은 'using ($vars)'로 받습니다. 믹스인이 호출자 블록에 문맥(예: 현재 브레이크포인트 이름)을 제공할 수 있습니다. 루프 상태를 소비자에게 노출해야 하는 반복/래퍼 믹스인에 강력합니다.
// Pass values back to the included block (Sass 3.3+)
@mixin each-breakpoint {
$breakpoints: (sm: 576px, md: 768px, lg: 1024px);
@each $name, $size in $breakpoints {
@media (min-width: $size) {
@content ($name, $size);
}
}
}
// Receive via #{...} - actually use the block like a function
@include each-breakpoint using ($name, $size) {
.container-#{$name} { max-width: $size; }
}미디어 쿼리를 위한 @content
가장 흔한 @content 사용 사례는 스타일을 올바른 @media 쿼리로 감싸는 respond-to 믹스인입니다. 호출자가 반응형 스타일 블록을 전달하면 믹스인이 올바른 미디어 쿼리 안에 배치합니다. 반응형 코드가 읽기 쉬워지고 브레이크포인트 정의가 한곳에 중앙화됩니다.
// Classic responsive mixin pattern
@mixin respond-to($breakpoint) {
@if $breakpoint == phone {
@media (max-width: 600px) { @content; }
} @else if $breakpoint == tablet {
@media (min-width: 601px) and (max-width: 900px) { @content; }
} @else if $breakpoint == desktop {
@media (min-width: 901px) { @content; }
}
}
.sidebar {
width: 300px;
@include respond-to(phone) {
width: 100%;
float: none;
}
@include respond-to(desktop) {
width: 350px;
}
}@content 패턴
@content는 많은 재사용 패턴을 구동합니다: @supports 래퍼, 키프레임 생성기, BEM용 수정자 클래스 생성기. 각각 호출자가 본문을 제공하고 믹스인이 상용구(선택자, at-규칙, 네임스페이스)를 처리합니다. 잘 구조화된 Sass 라이브러리가 유연하고 합성 가능한 API를 제공하는 방식입니다.
// Wrapper for @supports (feature queries)
@mixin supports-flex { @supports (display: flex) { @content; } }
// Keyframes generator
@mixin keyframes($name) {
@keyframes #{$name} { @content; }
}
@include keyframes(fade-in) {
from { opacity: 0; }
to { opacity: 1; }
}
// Modifier generator
@mixin modifier($name) {
&--#{$name} { @content; }
}
.button {
@include modifier(primary) { background: blue; }
@include modifier(danger) { background: red; }
}@content 사용 사례
@content는 문맥 래퍼(media/supports/keyframes), 확장 훅(기본 스타일 + 사용자 정의 추가), 조건부 출력을 가능하게 합니다. Sass의 고차 함수에 해당합니다. 믹스인이 프레임워크이고 @content가 콜백입니다. 유연하고 재사용 가능한 스타일 유틸리티를 만들려면 @content를 익히세요.
// 1. Context wrappers (@media, @supports, @keyframes)
@mixin mobile { @media (max-width: 767px) { @content; } }
// 2. Reset/normalize hooks
@mixin base-styles {
box-sizing: border-box;
margin: 0;
@content; // allow components to add more
}
// 3. Debugging/profiling wrappers
@mixin timed {
$start: systime();
@content;
// log elapsed...
}
// 4. Conditional output
@mixin if-dark($is-dark) {
@if $is-dark { @content; }
}모듈 시스템(@use / @forward)
@use와 @import
@use는 적절한 모듈 시스템으로 @import를 대체합니다. 네임스페이싱이 충돌을 막고, 모듈은 한 번만 로드되며(캐시), -나 _로 시작하는 멤버는 비공개(노출되지 않음)이고, 'with'가 기본값을 명시적으로 설정합니다. @import의 모든 구조적 문제를 해결합니다. 모든 새 Sass 코드에는 @use를 사용하세요.
// @use is the modern module system (replaces @import)
// Key improvements:
// 1. Members are namespaced (no global pollution)
// 2. Modules load ONCE (cached, no duplicate execution)
// 3. Privacy: members starting with - or _ are private
// 4. Explicit configuration with 'with'
// _shapes.scss
$radius: 4px;
@mixin rounded { border-radius: $radius; }
@mixin -internal { /* private */ } // not exposed
// app.scss
@use 'shapes'; // namespace: shapes
@use 'shapes' as s; // namespace: s
@use 'shapes' as *; // no namespace (global)
.card { @include shapes.rounded; } // via namespace@forward
@forward는 다른 모듈의 멤버를 자신의 것으로 만들지 않고 다시 내보냅니다. 폴더 내용을 모으는 배럴/인덱스 파일에 완벽합니다. @forward는 멤버 제외를 위한 'hide'와 재내보내기 시 이름 변경을 위한 'as prefix-*'를 지원합니다. 라이브러리나 폴더의 깔끔한 공개 API 를 만드는 데 사용하세요.
// @forward re-exports members from another module
// Useful for building index/barrel files
// sass/abstracts/_index.scss
@forward 'variables'; // exposes _variables.scss members
@forward 'functions';
@forward 'mixins';
// Now consumers can import the whole folder at once:
// app.scss
@use 'abstracts' as *; // gets variables + functions + mixins
// @forward can rename or hide members
@forward 'buttons' hide button-styles;
@forward 'forms' as form-*; // prefix all members with 'form-'비공개 멤버(- 접두사)
이름이 -나 _로 시작하는 멤버는 비공개이며, 자신의 파일 안에서는 쓸 수 있지만 @use나 @forward로 노출되지 않습니다. 모듈이 구현 세부를 숨기고 공개 API만 노출할 수 있습니다. 내부 도우미에는 - 접두사를 사용해 모듈 인터페이스를 깔끔하고 안정적으로 유지하세요.
// _math-helpers.scss
@function -internal-double($n) {
@return $n * 2;
}
@function public-times-two($n) {
@return -internal-double($n); // OK - same file
}
// Public function usable via @use
@function scale($n, $factor: 2) {
@return -internal-double($n) * $factor;
}
// app.scss
@use 'math-helpers';
.val { width: math-helpers.scale(10); } // OK
// .val { width: math-helpers.-internal-double(10); } // ERROR - private모듈 설정(with)
'with ($var: value, ...)'는 로드 시 모듈의 !default 변수를 설정합니다. @import의 전역 변수 덮어쓰기 패턴을 대체하는 현대적이고 범위가 지정된 방식입니다. 설정은 모듈의 첫 @use에만 적용되며 이후 @use는 설정된 모듈을 재사용합니다. 라이브러리에 테마를 적용하는 방법입니다.
// _theme.scss
$primary: blue !default;
$radius: 4px !default;
@mixin button {
background: $primary;
border-radius: $radius;
}
// app.scss - configure on @use
@use 'theme' with (
$primary: #ff6600,
$radius: 8px,
);
.btn { @include theme.button; }
// background: #ff6600; border-radius: 8px;
// 'with' only works for variables marked !default in the module.
// Configuration must happen at the FIRST @use of that module.모듈 모범 사례
모듈 모범 사례: @use 사용(@import 아님), 짧고 명시적인 네임스페이스 선호, _index.scss에서 @forward로 폴더 집계, 내부 도우미를 -로 비공개 표시, !default 변수에 'with'로 라이브러리 설정, 표준 함수에는 내장 sass:* 모듈 사용. 코드를 모듈적이고 유지보수 가능하게 유지합니다.
// 1. Always use @use, never @import (deprecated)
// 2. Use explicit namespaces for clarity
@use 'sass:math'; // built-in module namespace: math
@use 'variables' as v; // short custom namespace
// 3. Use @forward in _index.scss barrel files
// components/_index.scss
@forward 'buttons';
@forward 'cards';
// 4. Keep members private with - prefix
@function -helper() { @return ...; }
// 5. Configure libraries with 'with', set !default on library vars
$brand: blue !default;
// 6. Use built-in modules: sass:math, sass:color, sass:string,
// sass:list, sass:map, sass:meta, sass:selector, sass:css디버깅(@debug / @warn / @error)
@debug
@debug는 컴파일 중 터미널에 소스 파일과 줄 번호와 함께 값을 출력합니다. 빌드를 중단하지 않습니다. 개발 중 변수를 검사하고 실행 흐름을 추적하며 계산을 검증하는 데 사용하세요. 배포 전에 @debug 문을 제거하거나 주석 처리하세요. 출력은 CSS가 아니라 stderr로 갑니다.
// @debug prints a message to the console during compilation
$base: 16px;
$size: 24px;
@debug "Calculating size...";
@debug "base is #{$base}, size is #{$size}";
@debug "ratio: " #{math.div($size, $base)};
// Console output during compile:
// _file.scss:5 DEBUG: Calculating size...
// _file.scss:6 DEBUG: base is 16px, size is 24px
// @debug does NOT stop compilation - just logs
// Use it to trace values while developing@warn
@warn은 컴파일 중 콘솔에 치명적이지 않은 경고를 출력하며 빌드는 계속됩니다. 폐기 예고, 폴백 동작, 라이브러리의 잠재적 오용 경고에 사용하세요. @warn은 기본적으로 스택 추적을 포함해 사용자가 경고 출처를 찾을 수 있습니다. @debug처럼 CSS 출력에는 나타나지 않습니다.
// @warn prints a warning to the console (does NOT stop compilation)
@mixin deprecated-mixin {
@warn "deprecated-mixin is deprecated; use new-mixin instead.";
/* ... styles ... */
}
// Useful for deprecation notices, potential issues
@warn "Variable $primary is not set, falling back to default.";
// With stack trace for locating the call site
@warn "Invalid value: #{$value}" {
// optional stack trace via meta.module-functions
}
// @warn is non-fatal - compilation continues.@error
@error는 치명적 오류를 발생시켜 컴파일을 즉시 중단합니다. 함수와 믹스인의 입력을 검증하는 데 사용하세요. 명확한 메시지로 오용을 일찍 잡는 것이 깨진 CSS를 출력하는 것보다 낫습니다. @error는 스택 추적을 포함합니다. 진짜 잘못된 상태에만 @error를, 복구 가능한 문제에는 @warn을, 검사에는 @debug를 사용하세요.
// @error stops compilation with an error message
@function divide($a, $b) {
@if $b == 0 {
@error "Cannot divide by zero: divide(#{$a}, #{$b})";
}
@return math.div($a, $b);
}
// In a mixin validating arguments
@mixin set-font-size($size) {
@if not $size {
@error "set-font-size requires a non-null $size, got #{$size}";
}
font-size: $size;
}
// @error halts the build - use for invalid inputs
// that would produce broken CSS.meta 모듈 함수
sass:meta는 내부 조회 기능을 제공합니다. type-of()는 값의 타입을, inspect()는 모든 값의 읽기 쉬운 문자열을 반환합니다(디버깅에 유용). *-exists 함수는 이름으로 변수/믹스인/함수 존재를 확인합니다. meta.get-function()은 호출 가능한 참조를 반환해 고차 패턴을 가능하게 합니다. 방어적 라이브러리 코드에 사용하세요.
@use 'sass:meta';
// Inspect values
meta.type-of(10px); // number
meta.type-of("hi"); // string
meta.type-of((a: 1)); // map
meta.inspect((a: 1, b: 2)); // (a: 1, b: 2) - readable representation
// Variable existence (within current scope)
meta.variable-exists("base"); // true if $base exists
meta.global-variable-exists("primary");
// Mixin/function existence
meta.mixin-exists("my-mixin");
meta.function-exists("my-func");
// Feature queries
meta.feature-exists("at-error"); // true
// Get a function reference (for higher-order use)
$fn: meta.get-function("lighten");검사 함수
type-of()(전역 또는 meta.type-of)는 값의 데이터 타입을 식별하므로 방어적 함수/믹스인 로직에 필수입니다. inspect()는 모든 Sass 값(맵과 중첩 리스트 포함)을 읽기 쉬운 문자열로 렌더링해 @debug 로깅에 완벽합니다. math.unit()/is-unitless()는 숫자를 검사합니다. 이 도구들로 개발 중 Sass 내부를 관찰할 수 있습니다.
@use 'sass:meta';
@use 'sass:math';
// type-of: get the type of any value
$value: 16px;
type-of($value); // number
type-of("hello"); // string
type-of(#fff); // color
type-of(true); // bool
type-of(null); // null
type-of(1 2 3); // list
type-of((a: 1)); // map
// inspect: readable debug output of complex values
$map: (primary: blue, secondary: green);
debug: inspect($map); // (primary: blue, secondary: green)
// unit / unitless for numbers
math.unit(16px); // px
math.is-unitless(16); // true
// Combine with @debug for tracing
@debug "got: #{inspect($map)}";Sass와 SCSS 문법
SCSS 문법(.scss)
SCSS(.scss)는 가장 인기 있는 Sass 문법입니다. CSS의 엄격한 상위 집합이라 유효한 CSS 파일은 모두 유효한 SCSS이므로 .css를 .scss로 바꾸고 Sass 기능을 점진적으로 추가할 수 있습니다. SCSS는 CSS처럼 중괄호와 세미콜론을 사용합니다. 새 프로젝트와 팀 도입에는 SCSS를 선택하세요.
// SCSS - Sassy CSS
// Uses braces {} and semicolons ;
// Superset of CSS - all CSS is valid SCSS
$primary: #3498db;
.button {
background: $primary;
&:hover {
background: darken($primary, 10%);
}
.icon {
width: 16px;
height: 16px;
}
}
// Pros: familiar to CSS devs, easy migration, widely adoptedSass 들여쓰기 문법(.sass)
Sass 들여쓰기 문법(.sass)은 중괄호와 세미콜론을 없애고 전적으로 들여쓰기에 의존합니다(Python이나 Stylus처럼). 더 간결하지만 원시 CSS를 .sass 파일에 그대로 붙여넣을 수 없고 들여쓰기 오류가 버그를 만듭니다. SCSS보다 덜 흔하지만 깔끔한 모습을 선호하는 개발자도 있습니다. 둘 다 동일한 CSS로 컴파일됩니다.
// Sass - indented syntax
// NO braces, NO semicolons - uses indentation only
// Removes CSS punctuation for a cleaner look
$primary: #3498db
.button
background: $primary
&:hover
background: darken($primary, 10%)
.icon
width: 16px
height: 16px
// Pros: less typing, cleaner visually
// Cons: can't paste CSS directly, less popular, error-prone indentation문법 간 변환
sass-convert(Sass에 포함)는 .scss와 .sass를 변환합니다. Sass 문법에서는 간결성을 위해 @mixin이 =, @include가 +가 됩니다. 문법 외에는 동일합니다. 같은 기능, 같은 출력 CSS입니다. 대부분의 팀은 CSS 호환성과 폭넓은 도구 지원 때문에 SCSS로 표 준화합니다.
// Convert SCSS to Sass (and vice versa) with the sass CLI:
// $ sass-convert style.scss style.sass
// $ sass-convert style.sass style.scss
// Bulk convert a folder:
// $ sass-convert --recursive --from scss --to sass scss/ sass/
// $ sass-convert --recursive --from sass --to scss sass/ scss/
// Key syntax differences:
// 1. SCSS uses { } and ; | Sass uses indentation
// 2. SCSS: @include mixin() | Sass: +mixin()
// 3. SCSS: @mixin name {} | Sass: =name
// 4. SCSS: @import "x" | Sass: same
// 5. Multi-line: SCSS needs ; | Sass just newlines언제 무엇을 쓸까
SCSS가 더 안전한 기본값입니다. 업계 표준이고 모든 CSS 파일이 유효한 SCSS이며 대부분의 문서/예제가 SCSS를 사용합니다. 들여쓰기 .sass 문법은 구두점을 싫어하는 개발자에게 매력적이지만 도구 지원이 좁고 새 팀원 온보딩이 어렵습니다. 프로젝트마다 하나를 선택해 일관되게 유지하세요.
// Use SCSS (.scss) when:
// - Starting a new project (most common choice)
// - Migrating an existing CSS codebase (CSS is valid SCSS)
// - Working on a team (most developers know SCSS)
// - Using CSS frameworks/libraries (they're usually SCSS)
// Use Sass (.sass) when:
// - You prefer minimal punctuation / Python-like syntax
// - Writing from scratch with no CSS to migrate
// - Personal preference for cleaner-looking source
// Both produce identical CSS. The choice is stylistic.
// IMPORTANT: don't mix .scss and .sass in the same project.흔한 함정
최신 Sass는 여러 레거시 기능을 폐기했습니다. 나눗셈에는 / 대신 math.div(), @import 대신 @use/@forward, 전역 lighten()/darken()/mix() 대신 sass:color/sass:math 모듈 함수를 사용하세요. sass-migrator 도구가 이런 마이그레이션을 자동화합니다. 컴파일 중 폐기 경고를 확인해 코드를 미래에도 안전하게 유지하세요.
// 1. Division: / is deprecated for math, use math.div()
@use 'sass:math';
width: math.div(100px, 2); // CORRECT
// width: 100px / 2; // DEPRECATED (may be CSS list separator)
// 2. @import is deprecated - use @use/@forward
@use 'variables'; // CORRECT
// @import 'variables'; // DEPRECATED
// 3. lighten()/darken() deprecated - use color.adjust
@use 'sass:color';
color.adjust($c, $lightness: 10%); // CORRECT
// lighten($c, 10%); // DEPRECATED
// 4. Global color functions deprecated - use sass:color module
color.mix(red, blue); // CORRECT (via @use 'sass:color')
// mix(red, blue); // DEPRECATED global function관련 Sass 스니펫
Copy-paste ready code for common tasks.
Variables
Store colors, spacing, and breakpoints in Sass variables.
Nesting
Mirror HTML structure and use the parent selector with &.
Mixins
Create reusable style groups with arguments and defaults.
Extend & Placeholders
Share styles across selectors with @extend and %placeholders.
Partials & @use
Split stylesheets into partials and load them with @use.
Functions
Define custom functions that return computed values.
Control Directives
Generate styles with @for, @each, and @if.
Operators
Use arithmetic, relational, and equality operators in Sass.
Was this helpful?