Friday, June 29, 2018

How to Use Implicit Track Sizing on Your CSS Grid

How to Use Implicit Track Sizing on Your CSS Grid

Up until now our CSS grid tutorials have focused largely on explicit values–track sizes which we’ve explicitly defined. We’ve used rows which are 200px high, or perhaps columns which are 1fr wide, and we’ve explicitly stated how many of them we want. But what if we don’t know (or don’t want to commit to) how many tracks we want? That’s where implicit values come into play–let’s take a look.

Starter Grid

Here’s a basic grid which you can fork to follow along. It gives us a grid container, with 9 grid items. No column widths or quantities have been defined yet, so each item fills the maximum width available:

Defining Just One Column

Let’s imagine that we want one column on the left, and that we know exactly how wide we want it: 300px. We can define that by adding grid-template-columns: 300px; to our grid container. But we won’t be given any other columns unless we explicitly define them:

That is, unless we explicitly say we want one of the grid items to be placed into (for example) column 3 on row 1:

That then gives us extra columns outside our defined grid because CSS Grid will use the available space and its auto-placement algorithm to figure out where everything else goes.

This is great, and Grid will make assumptions even if we want to have more columns, without us having to define each one. But what if we want those implied tracks, however many there are, to have a specific width? That’s where grid-auto-columns comes into play.

Say “Hello” to grid-auto-columns

If we want all columns besides the first to be 100px wide, we could implicitly state that:

Paired with our explicit value, we get the best of both worlds. Here we’re saying that we want the first column to be 1fr (that it takes up one fraction of whatever space is left–auto would have the same effect here) and that any other columns after that should be 100px precisely:

This gives us the following:

And if we state that item 3 should actually be placed in column 5, on row 1, Grid knows how wide to make any additional columns because it’s implied.

We’re not limited to pixel values here either; we could use fraction units, em units, even the minmax() notation which we’ve discussed in previous tutorials.

Not Forgetting grid-auto-rows

It almost goes without saying that grid-auto-rows will do the same for rows as grid-auto-columns does for columns. Here’s an example, where all rows but the first two are fixed at a height of 200px.

Conclusion

Many of Grid’s properties have default values which will look after you in case you don’t define anything different, but on some occasions we need to at least imply what we want. With implicit track sizing we can imply what size any extra rows or columns should be, if they’re ever needed.

Read More


No comments:

Post a Comment