> 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.

# Variables & Nesting

## Variables

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

```scss
$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).

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

### SCSS variable vs CSS custom property

|                  | SCSS `$var`                        | CSS `--var`                |
| ---------------- | ---------------------------------- | -------------------------- |
| Thời điểm        | Compile-time, biến mất sau compile | Runtime, tồn tại trong CSS |
| Thay đổi runtime | Không                              | Có (JS đổi được)           |
| Dùng khi         | Giá trị cố định lúc build          | Theme đổi động, dark mode  |

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

```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.

```scss
.card {
  padding: 16px;

  .card__title {
    font-size: 20px;
  }

  .card__body {
    color: #333;
  }
}
```

Compile ra:

```css
.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.

```scss
.btn {
  color: white;

  &:hover {
    opacity: 0.9;
  }

  &--primary {
    background: $primary;
  }

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

Compile ra:

```css
.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.

```scss
.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.
