CSS MIN/MIX HEIGHT AND WIDTH

In CSS min, max, and regular heigh/width properties control how large or small an element can become.

Width

.box {
  width: 500px;
  min-width: 300px;
  max-width: 800px;
}
  • width → normal/desired width
  • min-width → element cannot become smaller than this
  • max-width → element cannot become wider than this

Height

.box {
  height: 400px;
  min-height: 200px;
  max-height: 600px;
}
  • height → normal/desired height
  • min-height → element cannot become shorter than this
  • max-height → element cannot become taller than this

Example

.box {
  width: 80%;
  min-width: 300px;
  max-width: 1000px;

  height: 50vh;
  min-height: 200px;
  max-height: 600px;
}

This means:

The box is normally 80% wide, but never less than 300px and never more than 1000px.

Its height is normally 50vh, but never less than 200px and never more than 600px.

Modern CSS: min(), max(), and clamp()

You can also use functions:

.box {
  width: min(90%, 1000px);
}

The width will be the smaller of 90% and 1000px.

.box {
  width: max(300px, 50%);
}

The width will be the larger of 300px and 50%.

Most useful:

.box {
  width: clamp(300px, 80%, 1000px);
}

clamp(minimum, preferred, maximum)

So:

clamp(300px, 80%, 1000px)

means minimum 300px → preferably 80% → maximum 1000px.

Comments