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

41 views Asked by At

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.

2

There are 2 answers

0
Temani Afif On BEST ANSWER

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>

0
Brett Donald On

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>