jabuj
jabuj

Reputation: 3649

CSS minmax(): prioritize max value

minmax: If max < min, then max is ignored and minmax(min,max) is treated as min..

I want to do something like

grid-template-columns: 1fr minmax(50%, 70vmin) 1fr;

I don't want the column to exceed 70vmin. According to specification, in situations where 70vmin happens to be less than 50%, it chooses the 50% as the column size, which I don't want. Is it possible to somehow invert this behavior?

Upvotes: 8

Views: 2500

Answers (3)

tsmigiel
tsmigiel

Reputation: 382

Try one of the following simpler solutions:

grid-template-columns: 1fr minmax(min(50%, 70vmin), 70vmin) 1fr;

Or in the non-grid case:

.class {
  min-width: min(50%, 70vmin);
  max-width: 70vmin;
}

It explicitly makes sure the min value is never bigger than the max value using the min() function. And still allows the content to set its width to something in between when possible.

Upvotes: 1

Temani Afif
Temani Afif

Reputation: 274175

What you are looking for is the combination of width/max-width like this:

width:50%;
max-width:70vmin;
  • If 70vmin > 50% then we will have at least 50% (our min boundary) and we will not exceed 70vmin
  • if 70vmin < 50% then we will have a width equal to 70vmin (our max boundary that suppress the min one)

You can achieve this using a simple div and margin:auto. No need for grid:

.grid-item {
  max-width: 70vmin;
  width: 50%;
  height: 50px;
  margin:auto;
  background: red;
};
 <div class="grid-item"></div>

In the above example we fixed the width to 50% so technically it won't be bigger. In case you want to have bigger than 50% when 70vmin is also bigger you can try the following combination:

.grid-container {
  display:flex;
  justify-content:center;
  margin:20px 0;
}

.grid-item {
  max-width: 70vmin;
  flex-basis:50%;
  height: 50px;
  background: red;
  
  white-space:nowrap;
}
<div class="grid-container">
  <div class="grid-item"> some text</div>
</div>

<div class="grid-container">
  <div class="grid-item"> some text some text some text some text some text some text some text some text some text</div>
</div>

We set the initial width using flex-basis to be at least 50%, we fix the max-width and the content can make the element to grow between 50% and 70vmin

Upvotes: 4

Michael Benjamin
Michael Benjamin

Reputation: 372139

That's what minmax() does, by definition. So try another approach.

Instead of this:

grid-container {
    grid-template-columns: 1fr minmax(50%, 70vmin) 1fr
}

Consider this:

grid-container {
    grid-template-columns: 1fr auto 1fr
}

grid-item {
    max-width: 70vmin;
    min-width: 50%;
}

Upvotes: 2

Related Questions