CSS Calc() function


The calc() function in CSS allows you to perform calculations and dynamically compute values for CSS properties. You can use it with length units, percentages, and various mathematical operations to create flexible and responsive layouts. The calc() function is particularly useful when working with elements that need to adapt based on the screen size, container size, or other changing factors.

css-calc-function


What is the calc() Function?

The calc() function enables you to perform mathematical operations, such as addition, subtraction, multiplication, and division, within the values of CSS properties. You can combine different units like pixels (px), percentages (%), ems (em), and rems (rem) and perform calculations directly in your CSS, allowing for more dynamic and flexible layouts.

 

Syntax of calc():

property: calc(expression); 
  • expression: A mathematical expression using any of the following operators: + (addition), - (subtraction), * (multiplication), / (division)

Example

 <!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS calc() Example</title>
  <style>
    /* Fixed header style */
    header {
      background-color: #3498db;
      color: white;
      height: 50px;
      text-align: center;
      line-height: 50px; /* Center the text vertically */
    }

    /* Section style that takes full height minus the header height */
    section {
      background-color: #2ecc71;
      height: calc(100vh - 50px); /* Full height minus header height */
      padding: 20px;
      color: white;
    }

    /* Simple content style */
    h2 {
      font-size: 24px;
      text-align: center;
    }
  </style>
</head>
<body>

  <header>
    My Header
  </header>

  <section>
    <h2>Content that takes full screen height minus the header</h2>
    <p>This section uses the CSS calc() function to adjust its height based on the viewport height, accounting for the fixed header.</p>
  </section>

</body>
</html>



OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.