CSS Nesting native: Tạm biệt Sass?
CSS Nesting đã có native trong browser. Liệu đã đến lúc bỏ Sass preprocessor và viết CSS thuần với nested syntax?
Năm 2024, CSS Nesting đã land trên tất cả major browsers. Đây là feature mà dev frontend chờ đợi hàng thập kỷ — và cũng là lý do chính nhiều người dùng Sass. Vậy Sass có còn cần thiết?
CSS Nesting syntax
Syntax khá quen thuộc nếu bạn đã dùng Sass/SCSS:
.nav {
display: flex;
gap: 1rem;
background: var(--surface);
& a {
color: var(--text);
text-decoration: none;
padding: 0.5rem 1rem;
border-radius: 0.5rem;
transition: background 0.2s;
&:hover {
background: var(--surface-hover);
}
&.active {
color: var(--primary);
font-weight: 600;
}
}
@media (max-width: 768px) {
flex-direction: column;
& a {
padding: 0.75rem;
}
}
}
Điểm khác biệt quan trọng: CSS native nesting ban đầu yêu cầu & prefix cho element selectors, nhưng spec đã update — giờ bạn có thể nest trực tiếp với relaxed parsing.
So sánh với Sass
Những gì CSS Nesting làm được tương đương Sass:
- Nested selectors với
& - Nest media queries bên trong rule
- Compound selectors (
&:hover,&.class)
Những gì Sass vẫn cần:
- Variables với logic — Sass variables support math, lists, maps. CSS custom properties chỉ là string substitution.
- Mixins — không có equivalent trong CSS native.
- @extend và placeholder selectors.
- Functions — Sass có built-in color functions, math functions phong phú hơn.
- Partials & imports — tổ chức file system.
Thực tế: Khi nào bỏ Sass được?
Nếu project của bạn dùng Sass chủ yếu để nesting + variables, hoàn toàn có thể chuyển sang CSS native:
/* Thay Sass variables bằng CSS Custom Properties */
:root {
--primary: oklch(65% 0.25 260);
--radius: 0.5rem;
--shadow: 0 2px 8px oklch(0% 0 0 / 0.1);
}
/* Nesting native + custom properties = đủ dùng */
.button {
padding: 0.75rem 1.5rem;
border-radius: var(--radius);
background: var(--primary);
box-shadow: var(--shadow);
&:hover {
filter: brightness(1.1);
}
&.outlined {
background: transparent;
border: 2px solid var(--primary);
}
}
Nếu bạn dùng Tailwind, PostCSS, hoặc CSS Modules — Sass càng ít lý do tồn tại.
Migration strategy
Đừng rewrite toàn bộ. Approach từng bước:
- File mới viết CSS native với nesting.
- Khi touch file Sass cũ, convert dần.
- Giữ Sass cho files dùng nhiều mixins/functions.
- Khi không còn file
.scssnào, remove Sass dependency.
Kết luận
CSS Nesting native không kill Sass hoàn toàn, nhưng nó loại bỏ lý do phổ biến nhất để dùng Sass. Với CSS custom properties + nesting + modern color functions, vanilla CSS đã đủ mạnh cho hầu hết projects. Sass vẫn có chỗ đứng cho large-scale design systems cần mixins và logic phức tạp.
Admin
Bình luận (0)
Đăng nhập để bình luận
Chưa có bình luận nào. Hãy là người đầu tiên!