CSS functions help make styling more flexible, dynamic, and responsive. They allow calculations, color manipulations, animations, and much more! Let's explore them with examples.
calc()
– Perform Calculations 🧮✅ Allows mathematical operations directly in CSS.
✅ Supports mixing units like px
, %
, em
, etc.
div {
width: calc(100% - 50px); /* Subtracts 50px from the container width */
height: calc(50vh + 20px); /* 50% of viewport height + 20px */
}
🌟 Use case: Adjusting sizes dynamically.
var()
– Use CSS Variables 🌈✅ Makes styles reusable and easy to manage.
✅ Allows you to define variables globally using :root
.
:root {
--primary-color: #3498db;
--spacing: 10px;
}
p {
color: var(--primary-color); /* Uses the primary color */
margin: var(--spacing); /* Uses the spacing value */
}
🌟 Use case: Keep colors and spacings consistent across your site.
rgb()
& rgba()
– Define Colors with Transparency ðŸŽâœ… rgb(r, g, b)
: Defines colors using Red, Green, and Blue values.
✅ rgba(r, g, b, a)
: Adds opacity (alpha) (0 = fully transparent, 1 = fully opaque).
div {
background-color: rgb(255, 0, 0); /* Pure red */
background-color: rgba(255, 0, 0, 0.5); /* 50% transparent red */
}