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/variables-nesting.md.

Sass SCSS variables scoping, selector nesting rules, and clean code practices.

Variables & Nesting

Variables

Khai báo biến bằng $. Dùng cho giá trị lặp lại: màu, font, spacing, breakpoint.

$primary: #2e8555;
$spacing: 8px;
$font-base: 'Inter', sans-serif;

.btn {
  background: $primary;
  padding: $spacing ($spacing * 2);
  font-family: $font-base;
}

Phạm vi biến

Biến khai báo ngoài cùng là global. Biến trong block { } là local. !global ép gán ra global, !default chỉ gán nếu biến chưa có giá trị (dùng cho config có thể override).

$primary: #2e8555 !default; // cho phép file dùng override trước khi import

SCSS variable vs CSS custom property

SCSS $varCSS --var
Thời điểmCompile-time, biến mất sau compileRuntime, tồn tại trong CSS
Thay đổi runtimeKhôngCó (JS đổi được)
Dùng khiGiá trị cố định lúc buildTheme đổi động, dark mode

Có thể kết hợp: gán CSS custom property từ biến SCSS.

:root {
  --color-primary: #{$primary};
}

Dấu #{} là interpolation, chèn giá trị SCSS vào nơi cần chuỗi/CSS.

Nesting

Lồng selector con bên trong cha, khớp cấu trúc DOM. Compile ra selector phân cấp.

.card {
  padding: 16px;

  .card__title {
    font-size: 20px;
  }

  .card__body {
    color: #333;
  }
}

Compile ra:

.card { padding: 16px; }
.card .card__title { font-size: 20px; }
.card .card__body { color: #333; }

Không lồng quá sâu (tối đa 3 cấp). Lồng sâu tạo selector dài, specificity cao, khó override.

Parent selector &

& tham chiếu selector cha. Dùng cho pseudo-class, state, và đặc biệt là BEM.

.btn {
  color: white;

  &:hover {
    opacity: 0.9;
  }

  &--primary {
    background: $primary;
  }

  &.is-active {
    font-weight: bold;
  }
}

Compile ra:

.btn { color: white; }
.btn:hover { opacity: 0.9; }
.btn--primary { background: #2e8555; }
.btn.is-active { font-weight: bold; }

&--primary ghép thành .btn--primary, hợp với quy ước BEM (Block, Element, Modifier) thường dùng trong AEM component.

Nesting properties

Thuộc tính cùng tiền tố (font-, margin-) có thể lồng. Ít dùng.

.text {
  font: {
    family: $font-base;
    size: 16px;
    weight: 700;
  }
}

Tips cho AEM

Đặt biến design system (màu, breakpoint, spacing) trong một partial dùng chung (styles/_variables.scss), import vào mọi component SCSS để đồng nhất. Selector gốc của component nên khớp sling:resourceType hoặc class BEM theo tên component để tránh xung đột style giữa các component.