For AI agents: the complete documentation index is available at https://nhanbe.id.vn/llms.txt, the full documentation bundle is available at https://nhanbe.id.vn/llms-full.txt, and this page is available as Markdown at https://nhanbe.id.vn/frontend/scss/control-flow-maps.md.

Using Sass SCSS control flow directives, loops, and map data structures.

Control Flow & Maps

SCSS có cấu trúc điều kiện và vòng lặp để sinh CSS động. Kết hợp với maps và lists để tạo style hàng loạt từ dữ liệu.

Lists

List là dãy giá trị, ngăn cách bằng dấu cách hoặc phẩy.

$sizes: 4px, 8px, 16px, 32px;
FunctionTác dụng
nth($list, $n)Lấy phần tử thứ n (1-indexed)
length($list)Số phần tử
append($list, $val)Thêm phần tử
index($list, $val)Vị trí của giá trị

Maps

Map là cặp key-value, dùng cho config có cấu trúc (màu theme, breakpoint).

$colors: (
  'primary': #2e8555,
  'danger': #d9534f,
  'muted': #6c757d
);

.alert {
  color: map-get($colors, 'danger');
}
FunctionTác dụng
map-get($map, $key)Lấy value theo key
map-has-key($map, $key)Kiểm tra tồn tại key
map-keys($map)List các key
map-values($map)List các value

@if / @else

@mixin theme($mode) {
  @if $mode == 'dark' {
    background: #1a1a1a;
    color: #fff;
  } @else if $mode == 'light' {
    background: #fff;
    color: #1a1a1a;
  } @else {
    background: gray;
  }
}

.panel {
  @include theme('dark');
}

@each

Lặp qua list hoặc map. Hữu ích nhất khi sinh nhiều class theo cùng pattern.

// lặp map: sinh class màu
@each $name, $color in $colors {
  .text-#{$name} {
    color: $color;
  }
}

Compile ra:

.text-primary { color: #2e8555; }
.text-danger { color: #d9534f; }
.text-muted { color: #6c757d; }
// lặp list
@each $size in $sizes {
  .p-#{$size} {
    padding: $size;
  }
}

@for

Lặp theo số, dùng cho grid, spacing scale.

// through: bao gồm cả 12; to: không bao gồm
@for $i from 1 through 12 {
  .col-#{$i} {
    width: percentage($i / 12);
  }
}

@while

Lặp theo điều kiện. Ít dùng, phần lớn trường hợp @for/@each đủ.

$i: 1;
@while $i <= 3 {
  .m-#{$i} { margin: #{$i * 4}px; }
  $i: $i + 1;
}

Interpolation trong control flow

#{} để chèn biến vào tên selector hoặc property. Bắt buộc khi tạo tên class động.

@each $name, $value in $breakpoints {
  .hide-#{$name} {
    display: none;
  }
}

Tips cho AEM

Dùng map cho design tokens (màu, spacing, breakpoint) đặt trong abstracts/, rồi @each sinh utility class hoặc CSS custom property. Cách này giữ một nguồn dữ liệu duy nhất, đổi token là toàn bộ style cập nhật, hợp với việc duy trì brand đồng nhất qua nhiều AEM component.

:root {
  @each $name, $color in $colors {
    --color-#{$name}: #{$color};
  }
}