๐จ CSS COURSE โ MODULE 13: CSS VARIABLES
๐ File: variables.md
๐จ CSS Variables (Custom Properties)
๐ Introduction
CSS Variables let you store values and reuse them anywhere.
๐ Instead of repeating colors, sizes, or styles ๐ You define them once and reuse them everywhere
๐ง 1. Defining Variables
Variables are created inside :root
:root {
--primary-color: blue;
--text-size: 16px;
}
โ -- is required for variables
๐ฏ 2. Using Variables
h1 {
color: var(--primary-color);
font-size: var(--text-size);
}
โ var() is used to access variables
๐จ 3. Real Example
<h1>Hello CSS</h1>
<p>Using variables</p>
:root {
--main-color: #4facfe;
--font-size: 18px;
}
h1 {
color: var(--main-color);
font-size: var(--font-size);
}
p {
color: var(--main-color);
}
๐ 4. Theme System (VERY IMPORTANT)
Light Theme
:root {
--bg-color: white;
--text-color: black;
}
Dark Theme
.dark {
--bg-color: black;
--text-color: white;
}
body {
background: var(--bg-color);
color: var(--text-color);
}
โ This is how dark mode works in real apps
โ๏ธ 5. Fallback Values
color: var(--main-color, red);
โ If variable is missing โ use red
๐งฉ 6. Why Use Variables?
Without variables:
h1 {
color: blue;
}
p {
color: blue;
}
a {
color: blue;
}
With variables:
:root {
--primary: blue;
}
h1,
p,
a {
color: var(--primary);
}
โ Easier to maintain โ Easy to change design
๐ง 7. Scope of Variables
.container {
--box-color: red;
}
.box {
color: var(--box-color);
}
โ Variables can be local or global
โ ๏ธ Common Mistakes
- Forgetting
--โ - Not using
var()โ - Overcomplicating variables โ
- Not organizing theme variables โ
๐ฏ Best Practice
๐ Always define:
colors
spacing
font sizes
theme values
๐งช Mini Exercise
Create:
- A color variable for primary theme
- A font-size variable
- A dark mode theme
- A card using variables
- A button using variables