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

Time:11-30

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

CodePudding user response:

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>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

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.

CodePudding user response:

Both are the same, the difference is the syntax.

Similar to

margin-top: 10px;
margin-bottom: 10px;
margin-left: 10px;
margin-right: 10px;

vs

margin: 10px 10px 10px 10px;
  • Related