In CSS, mathematical functions allow you to perform calculations within your stylesheets. This enables you to create more dynamic and responsive layouts by applying mathematical operations to various properties.
CSS supports basic arithmetic operations such as addition, subtraction, multiplication, and division.
/* Basic math in CSS */
.element {
width: 100px + 20px; /* Result: 120px */
height: 200px - 50px; /* Result: 150px */
font-size: 16px * 2; /* Result: 32px */
margin-left: 50px / 2; /* Result: 25px */
}
You can convert units within mathematical operations, making it easy to work with different units.
/* Unit conversion in CSS math */
.element {
width: 50% + 20vw; /* Result: 70% + 20vw */
height: 100px + 2rem; /* Result: 100px + 2rem */
}
Use CSS variables with mathematical functions for dynamic and reusable styles.
/* Dynamic values with variables and math */
:root {
--base-font-size: 16px;
}
.element {
font-size: var(--base-font-size) * 1.5; /* Result: 24px */
}
The 'calc()'
function allows you to perform complex calculations and mix different units.
/* Use calc() for complex calculations */
.element {
width: calc(50% + 20px); /* Result: 50% + 20px */
padding: calc(2em + 10px) calc(1em - 5px); /* Result: 2em + 10px, 1em - 5px */
}
Combine mathematical functions with viewport units for responsive design.
/* Viewport units and math for responsive design */
.element {
width: calc(50vw - 20px); /* Result: 50vw - 20px */
font-size: calc(1.5vw + 1rem); /* Result: 1.5vw + 1rem */
}
Use math for dynamic transformations in CSS.
/* Dynamic transformation with math */
.element {
transform: rotate(calc(45deg / 2)); /* Result: rotate(22.5deg) */
}
Mathematical functions in CSS provide a powerful way to create dynamic and responsive designs. From basic arithmetic to complex calculations using calc(), these functions allow you to manipulate values and units within your stylesheets. By leveraging mathematical functions, you can create more flexible and adaptive layouts, making your stylesheets more efficient and easier to maintain. Happy Coding! ❤️