Search code examples
cssgridcss-gridminmax

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?


Solution

  • 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