5

I recently realized that you can use the CSS function clamp() in combination with width to set a "max width" and "min width". I am wondering what the fundamental difference is when using width + clamp() over min-width, width, max-width.

In other words, how does this...

.item {
   width: 100%;
   max-width: 200px;
   min-width: 100px;
}

...differ from this...

.item {
   width: clamp(100px, 100%, 200px);
}
TylerH
  • 20,799
  • 66
  • 75
  • 101
Pat Murray
  • 4,125
  • 7
  • 28
  • 33

1 Answers1

7

I am wondering what the fundamental difference is

They are completely different so it's wrong to assume they are the same. I can give you a lot of examples where they behave differently but here is only one that should be enough to demonstrate that they are not the same:

.item1 {
  width: 100%;
  max-width: 300px;
  min-width: 200px;
}

.item2 {
  width: clamp(200px, 100%, 300px);
}

.container {
  display: flex;
  height:80px;
  margin:10px;
  width:150px;
  border: 2px solid;
}

.container>* {
  background: red;
}
<div class="container">
  <div class="item1"></div>
</div>
<div class="container">
  <div class="item2"></div>
</div>

In the below, using min-width will set a minimum boundary for the shrink effect (you get an overflow) while it's not the case when using clamp()

In most of the cases, you may not notice any difference but keep in my mind that they are indeed different.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • Maybe I'm wrong or missing something but setting `display: block` on `.container` (need also `height:100%` on items or you won't see them) the items will both correctly overflow, the containing is an effect from flexbox, `clamp` is setting correctly the min value requested if you look via devtools. So I guess the point is not really `clamp` per se but *where/how* it is applied right? – Gruber Nov 22 '22 at 04:03
  • @Gruber I doesn't really matter if it's flexbox or something else. I took the first example I had in mind to show that we don't get the same *final* result which mean both aren't the same. If both were the same (like assumed by the OP) then they should always produce the same result whatever the code configuration. Both can be used in most of the cases to get the same result but we cannot say they are exactly the same. – Temani Afif Nov 22 '22 at 08:39