csscss-gridpercentagefractions

CSS Grid: What is the difference between fraction vs percentage?


How are the fractions different to percentage? Is there any difference in the below codes?

grid-template-columns: 1fr 1fr 1fr 1fr;
/* --------vs-----------*/
grid-template-columns: 25% 25% 25% 25%;

They visually appear the same. Thanks for your help.


Solution

  • It's not only about gaps, the content of the elements impact the sizing of 1fr.

    In the below example there is no gap and the result is not the same.

    .d1, .d2 {
      display: grid;
      margin-bottom: 2em;
      border: 3px solid black;
    }
    
    .d1>*, .d2>* {
      height: 50px;
      background: #df00007f;
      white-space: nowrap;
      outline: 1px solid;
    }
    
    .d1 {
      grid-template-columns: repeat(4, 25%);
    }
    
    .d2 {
      grid-template-columns: repeat(4, 1fr);
    }
    <div class="d1">
      <div>25%</div>
      <div>25%</div>
      <div>a very long content here to illustrate</div>
      <div>25%</div>
    </div>  
    
    <div class="d2">
      <div>1fr</div>
      <div>1fr</div>
      <div>a very long content here to illustrate</div>
      <div>1fr</div>
    </div>

    This won't happen if you consider minmax(0,1fr) instead

    .d1, .d2 {
      display: grid;
      margin-bottom: 2em;
      border: 3px solid black;
    }
    
    .d1>*, .d2>* {
      height: 50px;
      background: #df00007f;
      white-space: nowrap;
      outline: 1px solid;
    }
    
    .d1 {
      grid-template-columns: repeat(4, 25%);
    }
    
    .d2 {
      grid-template-columns: repeat(4, minmax(0,1fr));
    }
    <div class="d1">
      <div>25%</div>
      <div>25%</div>
      <div>a very long content here to illustrate</div>
      <div>25%</div>
    </div>  
    
    <div class="d2">
      <div>1fr</div>
      <div>1fr</div>
      <div>a very long content here to illustrate</div>
      <div>1fr</div>
    </div>