{}
để nhóm chúng một cách hợp lý, giúp đoạn mã ngắn gọn và dễ đọc hơn..parent { color: blue;}.parent .child { font-size: 16px;}
.parent { color: blue; .child { font-size: 16px; }}
&
tương ứng với selector cha, rất hữu ích khi bạn muốn áp dụng pseudo-classes, pseudo-elements hay các combinators:.button { background: navy; &:hover { background: darkblue; } &.active { border: 2px solid gold; } &::before { content: '★'; }}
.container { width: 100%; @media (min-width: 768px) { width: 80%; .inner { padding: 20px; } }}
&
để tham chiếu selector cha khi cần.Tính Năng | SCSS/SASS | CSS Nesting (Native) |
---|---|---|
Biến (Variables) | Hỗ trợ biến như $primary-color: #007bff; | Dùng custom properties CSS ( --primary-color ) hỗ trợ động |
Mixin | Hỗ trợ mixins tái sử dụng block code | Không hỗ trợ, dùng custom properties & utility classes thay thế |
Vòng lặp & hàm | Hỗ trợ vòng lặp, hàm tính toán phức tạp | Chỉ hỗ trợ vài hàm cơ bản như calc() , không có vòng lặp |
Quản lý file | Cho phép chia nhỏ file với partials và import | Hạn chế, chỉ có @import truyền thống, kém hiệu quả |
Quy trình build | Cần biên dịch thành CSS thực thi trên trình duyệt | Không cần biên dịch, giảm phức tạp workflow |
.card { background: white; border-radius: 8px; box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1); padding: 16px; transition: transform 0.2s;
&:hover { transform: translateY(-4px); }
.title { font-size: 1.5rem; color: #333; margin-bottom: 8px; }
.content { font-size: 1rem; color: #666; line-height: 1.5; }
.button { background: #007bff; color: white; padding: 8px 16px; border-radius: 4px; text-decoration: none;
&:hover { background: #0056b3; } }
@media (max-width: 600px) { padding: 12px;
.title { font-size: 1.25rem; } }}
<div class="card"> <h2 class="title">Card Title</h2> <p class="content">This is the card content.</p> <a href="#" class="button">Learn More</a></div>
.title
, .content
, .button
được lồng trong .card
.&
cho trạng thái hover của .card
và .button
..nav { display: flex; gap: 16px; padding: 16px; background: #f8f9fa;
.nav-item { text-decoration: none; color: #333; font-weight: 500;
&:hover { color: #007bff; }
&.active { color: #007bff; border-bottom: 2px solid #007bff; } }
@media (max-width: 768px) { flex-direction: column; gap: 8px; }}
/* Không nên */.parent { .child { .grandchild { .great-grandchild { color: blue; } } }}
/* Nên */.parent .child { color: blue;}
&
Một Cách Hợp Lý&
khi thực sự cần thiết (pseudo-classes, pseudo-elements, combinators) để mã sạch và dễ hiểu.:root { --primary-color: #007bff;}
.button { background: var(--primary-color); &:hover { background: darkblue; /* SCSS có thể hỗ trợ hàm thao tác màu tốt hơn */ }}
@supports selector(&)
để hỗ trợ fallback cho trình duyệt không hỗ trợ CSS nesting.@supports selector(&) { .parent { .child { color: blue; } }}
@supports not selector(&) { .parent .child { color: blue; }}
@layer
.@layer base { .component { .child { color: blue; } }}