Search code examples
cssclamp

How does clamp() differ from setting width, max-width, & min-width?


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);
}

Solution

  • 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 first rectangle, 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.