skip to Main Content

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

grid-template-columns: 1fr 1fr 1fr 1fr;

grid-template-columns: 25% 25% 25% 25%;

They visually appear the same. Thanks for your help.

2

Answers


  1. Yes, there is a difference, which you can see if you add some gaps. Percentage widths are calculated early and depend only upon the width of the grid. Fractional widths are calculated late, after the widths of everything else have been taken into account, including gaps.

    .d1, .d2 {
      display: grid;
      margin-bottom: 2em;
      border: 3px solid black;
    }
    
    .d1>*, .d2>* {
      height: 50px;
      background: #df00007f;
    }
    
    .d1 {
      grid-template-columns: repeat(4, 25%);
      gap: 1em;
    }
    
    .d2 {
      grid-template-columns: repeat(4, 1fr);
      gap: 1em;
    }
    <div class="d1">
      <div>25%</div>
      <div>25%</div>
      <div>25%</div>
      <div>25%</div>
    </div>  
    
    <div class="d2">
      <div>1fr</div>
      <div>1fr</div>
      <div>1fr</div>
      <div>1fr</div>
    </div>
    Login or Signup to reply.
  2. 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>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search