CSS Variables & Functions
Modern CSS gives us powerful tools like variables and math functions to create dynamic, scalable, and easier-to-maintain stylesβjust like in real programming.
πΉ CSS Variables (Custom Properties)
CSS variables let you store values and reuse them anywhere in your styles.
β Declaring & Using Variables
:root {
--primary-color: #007bff;
--padding-base: 1rem;
}
.button {
background-color: var(--primary-color);
padding: var(--padding-base);
}- Use
:rootto define global variables. - Access using
var(--variable-name)
β Scope Example
.card {
--shadow-color: rgba(0, 0, 0, 0.2);
box-shadow: 0 4px 6px var(--shadow-color);
}π― Variables can be scoped to specific elements!
πΉ calc() Function
calc() lets you perform math inside CSS, mixing units or adjusting spacing.
β Examples:
.container {
width: calc(100% - 60px);
}
.card {
padding: calc(1rem + 10px);
}You can use:
+,-,*,/(with proper spacing)- Combine
%,px,rem, etc.
πΉ min() and max()
min(A, B): Picks the smaller of the two.max(A, B): Picks the larger.
β Example:
.section {
width: min(90vw, 1200px); /* Responsive max width */
}.card {
padding: max(1rem, 20px);
}πΉ clamp() β Responsive Sizing Made Easy
Clamp lets you set a fluid value with boundaries.
font-size: clamp(1rem, 2.5vw, 2rem);- Min: 1rem
- Preferred: 2.5vw
- Max: 2rem
π― Clamp is perfect for typography, padding, margins, etc.
π§ Combine Them!
:root {
--gap: 2rem;
}
.grid {
display: grid;
gap: clamp(1rem, 2vw, var(--gap));
}This makes layout spacing fluid, scalable, and readable.
β Summary Covered
--variablesandvar()usage and scopecalc()for inline calculationsmin(),max()for conditional sizingclamp()for fluid responsiveness- Practical use cases and combos
