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/mixins-functions.md.

Authoring reusable Sass SCSS mixins and custom functions.

Mixins & Functions

Mixins

Mixin là khối style tái sử dụng. Khai báo bằng @mixin, dùng bằng @include. Mixin chèn ra nhiều dòng CSS.

@mixin flex-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

.box {
  @include flex-center;
}

Mixin có tham số

@mixin button($bg, $color: white) {
  background: $bg;
  color: $color;
  border: none;
  padding: 8px 16px;
}

.btn-primary {
  @include button(#2e8555);
}

.btn-warning {
  @include button(#f0ad4e, #333); // override default
}

Tham số mặc định và đặt tên

@mixin box($padding: 8px, $radius: 4px) {
  padding: $padding;
  border-radius: $radius;
}

.card {
  @include box($radius: 8px); // chỉ định tên, bỏ qua thứ tự
}

Content block

@content cho phép truyền cả block style vào mixin. Rất hợp cho media query.

@mixin respond($breakpoint) {
  @media (min-width: $breakpoint) {
    @content;
  }
}

.container {
  width: 100%;

  @include respond(768px) {
    width: 750px;
  }
}

Functions

Function trả về một giá trị (không chèn CSS rule). Khai báo bằng @function, trả về bằng @return.

@function rem($px, $base: 16px) {
  @return ($px / $base) * 1rem;
}

.title {
  font-size: rem(24px); // 1.5rem
}

Khác biệt cốt lõi:

MixinFunction
Trả vềKhối CSS (declarations)Một giá trị
Gọi bằng@includeDùng như giá trị prop: fn()
Dùng khiNhóm style lặp lạiTính toán giá trị

Built-in functions hay dùng

FunctionTác dụng
lighten($c, $amt) / darkenLàm sáng/tối màu
rgba($c, $alpha)Thêm alpha cho màu
mix($c1, $c2, $weight)Trộn hai màu
percentage($num)Đổi sang phần trăm
map-get($map, $key)Lấy giá trị từ map
if($cond, $a, $b)Toán tử điều kiện
.btn:hover {
  background: darken($primary, 10%);
}

.overlay {
  background: rgba($primary, 0.5);
}

Lưu ý dart-sass mới khuyến nghị dùng module sass:color, sass:math thay cho một số function global (vd math.div() thay cho /). Với toolchain AEM cũ, function global vẫn chạy nhưng có thể có cảnh báo deprecation.

Tips cho AEM

Tập hợp mixin chung (responsive breakpoint, typography, truncate text) vào styles/_mixins.scss. Mixin respond() dùng map breakpoint thống nhất giúp responsive nhất quán giữa các AEM component.

$breakpoints: (
  'sm': 576px,
  'md': 768px,
  'lg': 992px
);

@mixin respond($name) {
  @media (min-width: map-get($breakpoints, $name)) {
    @content;
  }
}