CSS Functions - johnverz22/webdev1-lessons GitHub Wiki
What Are CSS Functions?
Think of CSS functions like magic calculators or special tools that help you do cool things with your styles. Just like math functions, they take inputs and give you an output!
Basic CSS Functions Everyone Should Know
1. calc() Function
The calculation superhero of CSS!
.container {
/* Do math directly in CSS! */
width: calc(100% - 20px);
/* Mix different units */
max-width: calc(600px + 10vw);
}
Real-World Examples
.sidebar {
/* Subtract fixed header height */
height: calc(100vh - 80px);
}
.responsive-grid {
gap: calc(10px + 2vmin);
}
2. Color Functions
rgb() and rgba()
.button {
/* Red, Green, Blue values (0-255) */
background-color: rgb(52, 152, 219);
/* Add transparency */
color: rgba(0, 0, 0, 0.5);
}
hsl() and hsla()
.gradient {
/* Hue, Saturation, Lightness */
background-color: hsl(120, 100%, 50%); /* Bright Green */
/* With alpha (transparency) */
color: hsla(240, 100%, 50%, 0.7); /* Transparent Blue */
}
3. Transform Functions
.card {
/* Rotate */
transform: rotate(45deg);
/* Scale */
transform: scale(1.2);
/* Multiple transforms */
transform: translateX(10px) rotate(45deg);
}
4. min() and max() Functions
.responsive-element {
/* Choose the smaller value */
width: min(300px, 100%);
/* Choose the larger value */
font-size: max(16px, 2vw);
}
5. clamp() Function
Perfect for responsive typography!
body {
/* Minimum, Preferred, Maximum */
font-size: clamp(16px, 2vw, 24px);
}
6. var() with Calculations
:root {
--spacing: 10px;
--multiplier: 2;
}
.container {
padding: calc(var(--spacing) * var(--multiplier));
}
Advanced Function Combos
Responsive Grid with Functions
.grid {
grid-template-columns: repeat(
auto-fit,
minmax(min(250px, 100%), 1fr)
);
}
Common Function Pitfalls
- Spaces matter!
calc(100% -20px)
is different fromcalc(100% - 20px)
- Always use spaces around operators
- Some functions work differently in different contexts
Browser Compatibility
- Most modern functions work in:
- Chrome
- Firefox
- Safari
- Edge
- Always check MDN for specific support
Practice Challenges
- Create a responsive card with
calc()
- Design a color scheme using
hsl()
- Make a fluid typography system with
clamp()
Learning Checklist
- Understand CSS function basics
- Use
calc()
for calculations - Work with color functions
- Create responsive designs
- Combine multiple functions
🌟 Pro Tips
- Functions make CSS more powerful
- They help create flexible designs
- Don't be afraid to experiment!