CSS Grid

Fractional unit

Grid introduces a grid specific length unit called the fractional unit (fr). fr helps us create flexible grid tracks and represents a fraction of the available space within the grid container.

When combined with non-fraction length units, the available space is the total space minus the space given to the non-fraction length units.

It's important to remember that the available space is divided up into fractions. Rows and columns will grow to equal lengths if there is enough space, but will shrink to contain just their content if there isn't enough available space.

Code example: rows

In this example we have specified that the first two rows should be 1fr in height. This ensures that they shrink and grow as needed and that they are equal in height.

Notice how the first row expands in response to the second row needing more space.

The last row (blue) does not have an explicitly set height and as a result is sized according to its contents.

.wrapper {
display: grid;
grid-template-rows: 1fr 1fr;
}
red
green
green 2
Nunc aliquet bibendum enim, facilisis gravida neque convallis a cras semper auctor neque, vitae tempus quam pellentesque nec nam aliquam? Egestas erat imperdiet sed euismod nisi porta lorem mollis aliquam!

Code example: limiting wrapper height

What happens if we explicitly set the last row's height to 1fr, and limit the grid container's height to a value that is too small to allow all rows to grow to equal heights? Well, row one and two isn't allowed to grow.

.wrapper {
display: grid;
grid-template-rows: 1fr 1fr 1fr;
height: 20rem;
}
red
green
green 2
Nunc aliquet bibendum enim, facilisis gravida neque convallis a cras semper auctor neque, vitae tempus quam pellentesque nec nam aliquam? Egestas erat imperdiet sed euismod nisi porta lorem mollis aliquam!