0
0
CSSmarkup~5 mins

CSS calc usage

Choose your learning style9 modes available
Introduction
CSS calc lets you do math inside your styles to mix different units and create flexible layouts.
When you want to set a width that is 100% of the container minus some fixed pixels.
When you need to combine percentages and pixels for padding or margin.
When you want to adjust font size based on viewport width minus a fixed size.
When you want to create responsive spacing that adapts but keeps some fixed gap.
Syntax
CSS
property: calc(expression);
The expression can use +, -, *, and / with spaces around operators.
You can mix units like %, px, em, rem inside calc.
Examples
Sets width to full container width minus 50 pixels.
CSS
width: calc(100% - 50px);
Adds 2 rem units plus 10 pixels for top margin.
CSS
margin-top: calc(2rem + 10px);
Font size grows with viewport width plus a base size.
CSS
font-size: calc(1vw + 1rem);
Sets height to half of 50% viewport height.
CSS
height: calc(50vh / 2);
Sample Program
This example shows a blue box that is almost full width but leaves 40 pixels total space (20px each side). The font size grows slightly with the viewport width for better readability on bigger screens.
CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>CSS calc Example</title>
<style>
  body {
    font-family: Arial, sans-serif;
    padding: 2rem;
  }
  .box {
    width: calc(100% - 40px);
    height: 100px;
    background-color: #4a90e2;
    margin: 20px auto;
    color: white;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: calc(1rem + 1vw);
    border-radius: 0.5rem;
  }
</style>
</head>
<body>
  <div class="box">This box uses calc() for width and font size.</div>
</body>
</html>
OutputSuccess
Important Notes
Always put spaces around operators inside calc() for better browser support.
calc() can be used anywhere CSS accepts length or size values.
You cannot use calc() inside some CSS properties that expect keywords only.
Summary
CSS calc() lets you do math with different units in styles.
Use it to create flexible, responsive layouts mixing fixed and relative sizes.
Remember to add spaces around operators and test on different screen sizes.