Có bao giờ bạn phát điên khi phải Ctrl+F và thay thế hàng chục lần chỉ để đổi một mã màu trong file CSS dài cả ngàn dòng chưa? Mình thì rồi, và đó là cơn ác mộng thực sự trong những năm đầu làm nghề.
Fortunately, CSS Custom Properties (or CSS variables) came into existence as a savior. This CSS Variable custom properties practical guide will help us write code according to the DRY (Don't Repeat Yourself) principle. It makes stylesheet maintenance neater, more flexible, and easier than ever.
What are CSS variables and why will they change your game?
CSS variables (or custom properties) are programmer-defined values that can be reused multiple times in a stylesheet. The benefit of CSS custom properties lies in the ability to reduce code repetition, making the source code many times easier to read and maintain.
Trước đây, khi muốn đổi màu chủ đạo của một website, bạn phải tìm từng dòng code chứa mã hex #007bff để sửa. Bây giờ, biến CSS là gì đã không còn xa lạ, nó cho phép bạn lưu mã màu đó vào một "biến" duy nhất. Khi cần thay đổi, bạn chỉ việc cập nhật giá trị tại một nơi, và toàn bộ giao diện sẽ tự động đổi theo.
For those who are Learning basic HTML and CSS for beginners, getting familiar with CSS variables early will help shape modern coding thinking. At Pham Hai, we always require interns to master this concept right from the first week. It's not just a feature, but a big step forward in making CSS a more logical language.
Basic syntax: Declare and call variables in 30 seconds
Để khai báo, bạn dùng tiền tố -- (ví dụ: --main-color: blue;) và để gọi biến, bạn sử dụng hàm var() (ví dụ: color: var(--main-color);).
Using CSS custom properties is really intuitive. You just need to remember the "two dashes" rule. Here's a basic example of CSS custom properties for beginners:
:root {
--primary-color: #3498db;
--padding-standard: 16px;
}
.button {
background-color: var(--primary-color);
padding: var(--padding-standard);
}
Chỉ với vài dòng code, bạn đã thiết lập xong một nền tảng vững chắc. Hàm var() sẽ lấy giá trị được lưu trữ và đắp thẳng vào thuộc tính CSS tương ứng.
Phạm vi biến: Toàn cục (:root) và cục bộ - Đặt đâu cho đúng?
Phạm vi biến trong CSS được quyết định bởi nơi bạn khai báo nó. Khai báo trong selector :root tạo ra biến toàn cục, trong khi khai báo ở một class cụ thể sẽ tạo ra biến cục bộ chỉ áp dụng cho phần tử đó và con của nó.
Khi bạn khai báo biến trong selector :root, biến đó tương đương với thẻ <html> và có thể được truy cập từ bất kỳ đâu trong tài liệu. Đây là nơi hoàn hảo để lưu trữ các giá trị của hệ thống thiết kế như màu sắc thương hiệu hay font chữ.
Ngược lại, phạm vi biến CSS cục bộ lại cực kỳ hữu ích khi bạn xây dựng các component độc lập. Ví dụ, một .card có thể có --card-bg: white;. Biến này sẽ không ảnh hưởng đến các phần tử nằm ngoài .card, giúp tránh xung đột code trong các dự án lớn.
Inheritance and Overriding: The Power of Cascading CSS Classes
Inheritance allows child elements to automatically receive variable values from the parent element. At the same time, you can easily override CSS custom properties values by redefining the variable in a more specific selector.
Tính kế thừa của biến CSS hoạt động giống hệt như các thuộc tính CSS thông thường như color hay font-family. Nếu một thẻ <div> cha có --text-color: black;, mọi thẻ <p> bên trong nó cũng sẽ "hiểu" biến này trừ khi bị chặn lại.
Overriding CSS also happens very naturally. If you want a particular button to have a different color, you just need to redeclare that variable inside the button's class:
.button-danger {
--primary-color: #e74c3c; /* Ghi đè giá trị màu xanh thành màu đỏ */
}
Fallback value: 'Option B' saves the day when the variable fails
Giá trị dự phòng CSS custom properties được thiết lập bằng cách thêm tham số thứ hai vào hàm var(). Nó giúp giao diện không bị vỡ nếu biến chính chưa được khai báo hoặc không hợp lệ.
Trong thực tế, đôi khi biến CSS có thể bị gõ sai tên hoặc chưa được tải kịp do lỗi mạng. Hàm var() cho phép bạn phòng hờ rủi ro này một cách thanh lịch:
.text {
color: var(--theme-color, #333333);
}
Nếu --theme-color không tồn tại, trình duyệt sẽ tự động sử dụng màu #333333. Kỹ thuật này đặc biệt quan trọng khi bạn viết các thư viện CSS để chia sẻ cho người khác dùng chung.
Practical application: From small things to 'doing big things' with CSS Variables
Practical applications of CSS variables range from building consistent design systems to creating complex interactive interfaces. It turns a static stylesheet into a flexible and intelligent CSS ecosystem.
When combined with layout techniques like A-Z Flexbox CSS Guide with Examples, CSS variables give you complete control over spacing and alignment through just a few parent-level declarations. Let's dive into the most common use-cases.
Create Dark Mode / Light Mode super fast with just a few lines of code
By overriding color variables based on data-theme properties or media queries, you can create dynamic themes with CSS variables extremely quickly. This is the most standard way to do dark mode and light mode today.
In the past, to make a dynamic theme, we had to write two separate CSS files and use JavaScript to change the files. Now everything boils down to one simple syntax:
:root {
--bg-color: #ffffff;
--text-color: #222222;
}
[data-theme="dark"] {
--bg-color: #121212;
--text-color: #f1f1f1;
}
body {
background-color: var(--bg-color);
color: var(--text-color);
}
Chỉ cần thay đổi thuộc tính data-theme trên thẻ <html> bằng một dòng JS nhỏ, toàn bộ màu sắc của trang web sẽ chuyển đổi mượt mà.
Manage consistent Spacing and Font Size systems for the entire project
CSS variables act as a source of truth for all font sizes, spacing, and styles. This helps maintain a consistent design system from start to finish of the project.
Thay vì hardcode các giá trị như margin: 15px hay padding: 20px rải rác khắp nơi, bạn nên gom chúng lại thành các biến như --space-sm, --space-md, --space-lg.
Điều này đặc biệt hữu ích khi thiết lập khoảng cách (gap) trong CSS Grid Layout toàn tập dễ hiểu. Bạn chỉ cần gọi gap: var(--space-md);, giao diện sẽ luôn đảm bảo sự thẳng hàng tăm tắp mà không sợ bị lệch pixel nào.
Responsive design is more flexible by changing variables in Media Queries
Instead of rewriting entire CSS blocks, you can simply update variable values inside media queries. This technique helps responsive design become much more compact and easier to control.
This is the core secret when Designing responsive websites with Media Query. Take a look at the following example:
:root {
--container-width: 100%;
}
@media (min-width: 768px) {
:root {
--container-width: 720px;
}
}
Bạn không cần phải lặp lại class .container { width: ... } nhiều lần. Thuộc tính tùy chỉnh sẽ tự động điều chỉnh theo kích thước màn hình, giúp giảm thiểu đáng kể dung lượng file CSS.
Dynamic interactions: Change 'the whole world' with just one line of JavaScript
Thay đổi CSS variable bằng JavaScript thông qua phương thức style.setProperty() cho phép bạn thao tác trực tiếp với giao diện mà không cần thêm bớt class rườm rà. Nó tạo ra cầu nối hoàn hảo giữa logic JS và giao diện CSS.
The DOM and CSSOM in modern browsers (as of 2026) handle CSS variable updates extremely well. When you get mouse coordinates from JavaScript and pass them to CSS variables, you can create 3D hover effects or very magical mouse cursor tracking:
document.documentElement.style.setProperty('--mouse-x', event.clientX + 'px');
With just this one line of code, CSS can receive real-time data from user actions.
Improve skills: Comparison and 'secrets' that not everyone knows
Để thực sự làm chủ và có thể tự tin viết một hướng dẫn toàn tập CSS custom properties, bạn cần phân biệt rõ nó với các công cụ cũ và biết cách tận dụng các tính năng CSS hiện đại như @property hay hàm tính toán.
Sass Variables vs CSS Custom Properties: Some are eight ounces, others are half a pound?
When comparing CSS custom properties and Sass variables, the core difference is that Sass variables are processed at compile-time, while CSS variables actually operate at runtime in the browser.
Many of you wonder, if you already have a CSS preprocessor like Sass/SCSS, why use CSS variables? Below is a quick comparison table based on Pham Hai's actual combat experience:
| Criteria | Biến Sass ($var) |
Biến CSS (--var) |
|---|---|---|
| Môi trường hoạt động | Compile-time | Runtime |
| Cập nhật bằng JS | Cannot | Absolutely possible |
| Tính kế thừa DOM | None (only according to SCSS file scope) | Yes (inherit according to the DOM tree) |
You can completely combine the two: Use Sass for complex loop logic and use CSS Variables for values that need to change dynamically in the browser.
Dùng hàm calc() kết hợp với biến để tính toán giá trị động
Hàm calc() khi kết hợp với biến CSS cho phép thực hiện các phép toán nội suy ngay trên trình duyệt. Nó giúp giao diện tự động co giãn tỷ lệ mà không cần viết thêm mã thừa.
For example, you want to create a padding that is always half the standard distance. Instead of creating a new variable, just do this:
.box {
padding: calc(var(--space-md) / 2);
}
This combination provides great computing power, helping UI elements automatically adapt to each other perfectly.
@property discovery: Allows the browser to 'understand' your variable
Cú pháp @property at-rule cho phép định nghĩa kiểu dữ liệu (syntax) và giá trị khởi tạo cho biến CSS. Nó tối ưu hóa hiệu suất render và cho phép animate các thuộc tính phức tạp một cách mượt mà.
Tính đến năm 2026, @property đã được hỗ trợ 100% trên tất cả các trình duyệt hiện đại (Baseline). Khi bạn đăng ký một biến với inherits: false, trình duyệt sẽ không phải tính toán lại toàn bộ cây DOM mỗi khi biến đó thay đổi, giúp cải thiện hiệu suất rõ rệt.
Nó là chìa khóa để Tạo animation CSS đẹp không cần JavaScript cho các thuộc tính phức tạp như gradient. Khi trình duyệt biết --gradient-angle là một góc (<angle>), nó có thể tạo hiệu ứng xoay (transition) mượt mà thay vì chuyển đổi giật cục.
@property --gradient-angle {
syntax: '<angle>';
initial-value: 0deg;
inherits: false;
}
In short, using CSS Custom Properties is not just a new technique but a change in coding thinking: towards modularity, ease of extension and maintenance. Don't hesitate, start applying it right from your smallest project, and I believe you won't want to go back to the old way of writing CSS anymore.
Have you used CSS Variables in any 'cool' projects? Share now in the comments section so everyone can learn together!
Lưu ý: Các thông tin trong bài viết này chỉ mang tính chất tham khảo. Để có được lời khuyên tốt nhất, vui lòng liên hệ trực tiếp với chúng tôi để được tư vấn cụ thể dựa trên nhu cầu thực tế của bạn.