📖 HTML & CSS Nâng cao - CSS Variables & Custom Properties
45 phút

CSS Variables & Custom Properties

Giới thiệu CSS Custom Properties

CSS Variables (custom properties) cho phép lưu trữ và tái sử dụng giá trị trong CSS.

Khai báo và sử dụng

Khai báo biến

:root {
  --primary-color: #3498db;
  --secondary-color: #2ecc71;
  --font-size-base: 16px;
  --spacing-unit: 1rem;
  --border-radius: 8px;
  --box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

Sử dụng biến

.button {
  background-color: var(--primary-color);
  padding: var(--spacing-unit);
  border-radius: var(--border-radius);
  box-shadow: var(--box-shadow);
}

Fallback values

.element {
  color: var(--undefined-color, #000000); /* Sử dụng fallback nếu biến không tồn tại */
  margin: var(--spacing, 10px) var(--spacing, 10px);
}

Scoped Variables

Local scope

.component {
  --local-color: #e74c3c;
  --local-spacing: 2rem;
}

.component .child {
  color: var(--local-color);
  padding: var(--local-spacing);
}

Theme switching

:root {
  --bg-color: #ffffff;
  --text-color: #333333;
  --primary: #3498db;
}

[data-theme="dark"] {
  --bg-color: #1a1a1a;
  --text-color: #ffffff;
  --primary: #2980b9;
}

body {
  background-color: var(--bg-color);
  color: var(--text-color);
}

Advanced Usage

Tính toán với calc()

:root {
  --base-size: 16px;
  --scale: 1.2;
}

h1 {
  font-size: calc(var(--base-size) * var(--scale) * 2);
}

h2 {
  font-size: calc(var(--base-size) * var(--scale) * 1.5);
}

Dynamic changes với JavaScript

// Thay đổi CSS variable
document.documentElement.style.setProperty('--primary-color', '#e74c3c');

// Đọc giá trị
const primaryColor = getComputedStyle(document.documentElement)
  .getPropertyValue('--primary-color');

Design Systems với CSS Variables

Design tokens

:root {
  /* Colors */
  --color-primary: #3498db;
  --color-secondary: #2ecc71;
  --color-danger: #e74c3c;
  --color-warning: #f39c12;
  
  /* Typography */
  --font-family-base: 'Inter', sans-serif;
  --font-size-sm: 0.875rem;
  --font-size-base: 1rem;
  --font-size-lg: 1.125rem;
  
  /* Spacing */
  --spacing-xs: 0.25rem;
  --spacing-sm: 0.5rem;
  --spacing-md: 1rem;
  --spacing-lg: 1.5rem;
  --spacing-xl: 2rem;
  
  /* Border radius */
  --radius-sm: 4px;
  --radius-md: 8px;
  --radius-lg: 16px;
}

Component styling

.button {
  font-family: var(--font-family-base);
  font-size: var(--font-size-base);
  padding: var(--spacing-sm) var(--spacing-md);
  border-radius: var(--radius-md);
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.button-primary {
  background-color: var(--color-primary);
  color: white;
}

.button-secondary {
  background-color: var(--color-secondary);
  color: white;
}

📝 Bài tập (1)

  1. Tạo design system sử dụng CSS custom properties

Bài học "CSS Variables & Custom Properties" - Khóa học "HTML & CSS Nâng cao"