The calc()
function in CSS allows you to perform mathematical operations on values dynamically. This is particularly useful when working with responsive designs, ensuring elements adjust based on different screen sizes and available space.
+
(Addition)-
(Subtraction)*
(Multiplication)/
(Division)While calc()
is powerful, it has limitations. You cannot use it for:
calc(red + blue)
does not work)calc(10px + 'em')
is invalid)calc(50% + 20px * 2)
may cause issues if not formatted correctly)vw
(viewport width) is a CSS unit that represents a percentage of the total width of the viewport. For example:
100vw
means 100% of the viewport width.50vw
means half of the viewport width.It is commonly used in responsive designs to ensure elements scale with the browser width.
Here are some examples of how you can use calc()
in CSS:
div {
width: calc(100% - 20px);
}
.box {
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 50px);
width: 100px;
height: 100px;
}
.sidebar {
width: calc(100vw / 3);
}
h1 {
font-size: calc(1rem + 2vw);
}
button {
width: calc(50% - 10px);
}
.column {
width: calc(33.33% - 20px);
float: left;
}
.box {
width: calc(70% - 50px);
}
Make a div
that takes 70% of the parent width but also subtracts 30px for margins.
Create a header
that is always 60px tall, ensuring the content starts 60px from the top.
Make a sidebar that takes up one-fourth of the screen width and adjusts dynamically.
Make a heading where the font size increases as the viewport width increases.
Build a grid where each column takes one-third of the available space but subtracts 20px for margins.