0
0
CSSmarkup~5 mins

Min and max functions in CSS

Choose your learning style9 modes available
Introduction

Min and max functions help you set sizes that adapt to different screen sizes. They make your design flexible and look good everywhere.

When you want a box to be at least a certain size but not too big.
When you want text to grow but not get too large on big screens.
When you want padding or margins to adjust between a minimum and maximum value.
When you want to combine fixed and flexible sizes for layout parts.
When you want to keep elements readable and usable on small and large devices.
Syntax
CSS
min(value1, value2, ...)
max(value1, value2, ...)

min() picks the smallest value from the list.

max() picks the largest value from the list.

Examples
The width will be the smaller of 300 pixels or 50% of the viewport width.
CSS
width: min(300px, 50vw);
The font size will be at least 1rem but can grow bigger if 2% of viewport width is larger.
CSS
font-size: max(1rem, 2vw);
Top and bottom padding will be at least 10px or 2% of container width, whichever is bigger. Left and right padding will be the smaller of 20px or 5% of viewport width.
CSS
padding: max(10px, 2%) min(20px, 5vw);
Sample Program

This example shows a blue box. Its width will never be more than 300 pixels or more than half the screen width, whichever is smaller. The font size grows but never gets smaller than 1rem. Padding also adjusts between minimum and maximum values. Resize the browser window to see the changes.

CSS
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>Min and Max Functions Demo</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 2rem;
    }
    .box {
      width: min(300px, 50vw);
      height: 150px;
      background-color: #4a90e2;
      color: white;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: max(1rem, 3vw);
      padding: max(10px, 2%) min(20px, 5vw);
      border-radius: 0.5rem;
      box-sizing: border-box;
      text-align: center;
    }
  </style>
</head>
<body>
  <div class="box" role="region" aria-label="Example box using min and max functions">
    Resize the browser window.<br />
    The box width and font size change between minimum and maximum values.
  </div>
</body>
</html>
OutputSuccess
Important Notes

Use units like px, rem, vw, or % inside min() and max().

Min and max help make your site look good on phones, tablets, and desktops without extra code.

Test by resizing your browser window or using device simulation in browser DevTools.

Summary

min() picks the smallest value, max() picks the largest.

They help create flexible, responsive sizes for elements.

Use them to keep sizes between limits for better design on all devices.