Day 2 - CSS Variables & Functions
Modern CSS allows you to use Variables to store values and Functions to perform calculations.
1. CSS Variables (Custom Properties)
Defining a value once and reusing it everywhere makes updating
themes easy. Variables usually start with -- and are
accessed using var().
Code:
/* CSS */
:root {
--primary-color: #e91e63;
--box-padding: 20px;
}
.box {
background-color: var(--primary-color);
padding: var(--box-padding);
}
:root {
--primary-color: #e91e63;
--box-padding: 20px;
}
.box {
background-color: var(--primary-color);
padding: var(--box-padding);
}
Output:
I use --primary-color (Pink)
I use --secondary-color (Blue)
Local Scope (Overriding):
You can redefine variables inside specific selectors.
I redefined --primary-color to Green!
2. Functions: calc()
Use calc() to perform math on CSS values. You can mix
units like % and px.
Code:
/* CSS */
.calc-box {
/* 100% width minus 40px constant space */
width: calc(100% - 40px);
}
.calc-fluid {
width: calc(100% / 3);
/* One third width */
}
.calc-box {
/* 100% width minus 40px constant space */
width: calc(100% - 40px);
}
.calc-fluid {
width: calc(100% / 3);
/* One third width */
}
Output:
Width: 100% - 40px
Width: 100% / 3