CSS Tutorial

Introduction

Edit Template
  • Home
  • /
  • CSS Maths Functions

CSS Tutorial

Introduction

Edit Template
  • Home
  • /
  • CSS Maths Functions

CSS Maths Functions

CSS provides math functions that allow you to dynamically calculate values for properties like width, height, margin, padding, and more. These functions make layouts more flexible and responsive, especially when dealing with mixed units or adaptive designs.

calc() Function

The calc() function lets you do basic math operations in your CSS. It supports +, -, *, and /.

				
					selector {
  property: value !important;
}

				
			

Subtracting from full width

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .box {
      width: calc(100% - 40px);
      background-color: lightcoral;
      padding: 10px;
      color: white;
    }
  </style>
</head>
<body>
  <div class="box">
    This box uses <code>calc(100% - 40px)</code> for width.
  </div>
</body>
</html>

				
			
Subtracting from full width Example

Explanation: This ensures that the box always adjusts to 100% of its parent container but leaves 40px for margin or other spacing.

max() Function

The max() function chooses the larger of two values and uses that as the final value.

Minimum width protection

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .max-box {
      width: max(300px, 50%);
      background-color: seagreen;
      padding: 10px;
      color: white;
    }
  </style>
</head>
<body>
  <div class="max-box">
    This box uses <code>max(300px, 50%)</code>. It will always be at least 300px wide.
  </div>
</body>
</html>

				
			

Use case: Ensures that the width never drops below 300px even on smaller screens.

Minimum width protection Eaxmple

min() Function

The min() function picks the smaller of two values to assign.

Maximum width control

				
					<!DOCTYPE html>
<html lang="en">
<head>
  <style>
    .min-box {
      width: min(400px, 80%);
      background-color: dodgerblue;
      padding: 10px;
      color: white;
    }
  </style>
</head>
<body>
  <div class="min-box">
    This box uses <code>min(400px, 80%)</code>. It won't go over 400px wide.
  </div>
</body>
</html>

				
			

 Use case: Prevents elements from growing too large on wide screens.

Scroll to Top