How to Calculate the Width of an Element with the CSS calc() Function
The usage of the CSS calc() function
In this snippet, you can find some examples, where we calculate the width of an element with the CSS calc() function. As we know, this function allows us to do simple calculations and determine the values of CSS properties right in CSS.
The calc() function is especially useful when you need to mix units. In our examples, we’ll mix percentages and pixels.
Let’s see the calc() function in use.
Example of using the calc() function:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.content-container {
display: flex;
padding: 40px 0;
background-color: #d7dade;
}
.right {
width: 100px;
background-color: #759ac9;
}
.left {
width: calc(100% - 100px);
background-color: #7cd47b;
}
</style>
</head>
<body>
<div class="content-container">
<div class="left">Some text</div>
<div class="right">Some text</div>
</div>
</body>
</html>
Result
In the example above, we set the display property of the container to “flex”. For the right <div> element, we specified the width, while for the left <div>, we used the calc() function to calculate its width.
Example of using the calc() function for the <div> element with the CSS display property:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
div {
border: 1px solid #0011ff;
}
.content-container {
padding: 20px 0;
}
.content-container div {
display: inline-block;
}
.right {
width: 90px;
}
.left {
width: calc(100% - 100px);
}
</style>
</head>
<body>
<div class="content-container">
<div class="left">Some text</div>
<div class="right">Some text</div>
</div>
</body>
</html>
Let’s see one more example, where we specify the float properties for each individual <div>. Then, we add the clear property with its "both" value to the "content-container" class.
Example of using the calc() function for the <div> element with float:
<!DOCTYPE html>
<html>
<head>
<title>Title of the document</title>
<style>
.content-container {
clear: both;
content: "";
display: table;
width: 100%;
padding: 40px 0;
background-color: #d1d2e3;
}
.right {
width: 100px;
background-color: #4b89b8;
float: right;
}
.left {
width: calc(100% - 100px);
background-color: #42d46d;
float: left;
}
</style>
</head>
<body>
<div class="content-container">
<div class="left">Some text</div>
<div class="right">Some text</div>
</div>
</body>
</html>