Hey everyone!
In this post I'm going to share with you some of the things I gathered about CSS Grid and how you can use it to build cleaner markups and consequently increase maintainability in your projects, to mention one of its many advantages.
CSS Grid is one of those many shiny technologies that seem to appear out of the blue and gain popularity really fast, which makes us think that is probably another hype thing. As we are used to that kind of thing in the web development world, most of us end up being skeptical about trying something new and seeing how things really work with that new technology.
For me, this happened with CSS Grid. In my case, I gave it a shot when I first heard about it and watched videos from Wes Bos' CSS Grid course. I remember finding it really interesting and daunting at the same time since it changes your mindset when building layouts. Also, I had the idea of not being able to use it in real-world projects because of its current support. If I wanted to use it I would have to add a lot of backward compatibility code, so that was a no-go for me.
It turns out I needed a little more research on the subject and I'm glad I did. This post is greatly inspired in this talk by Morten Rand-Hendriksen.
Some history
CSS Grid, as any other specification officially approved and shipped in browsers, has been through a lot of discussion and implementations since it was first presented to W3C by a Microsoft team in 2012. As the idea of a grid layout had been floating around for more than 20 years already, that wasn't the first specification to be proposed (more info here).
The difference was that, in this time, the Microsoft team also presented a real implementation of the grid layout. That helped at evaluating the proposal in a more realistic way. Also, several people started playing with it and spreading the word about it, so many real examples of a grid layout started to come out. That, for me, was one of the things that really helped CSS Grid to quickly gain popularity in the community, which is amazing!
Since then, the specification has changed a lot and most of the work that was done before that time was also taken into consideration. With that, a lot of additions and clean-ups were made to the initial proposal.
With such enthusiasm about the new cool kid on the block, by the end of the first semester of 2017, Chrome, Firefox, Opera, and Safari had shipped support for CSS Grid. Take a look at its current support:
The support mentioned for Opera is for Opera Mobile only.
Interestingly, Microsoft was the last company to ship the updated version of grid layout in Edge. As for IE10 and IE11, the supported grid layout version is still the old one and it looks like those are not getting updated.
CSS Grid lingo
As with any other technology, it is a good starting point to get to know the lingo related to it. In this section, I'll list the basic concepts you should have in mind before start playing with CSS Grid.
Container
This is the root of your grid layout and wraps up all the other items inside your grid. In order to define a grid container, you basically set the display
property to grid
in the element you want to be your grid container.
Even though you will not see any difference after applying that rule, now you have a grid container you can start laying items on.
Item
A grid item is every direct child of your grid container. In the example above you can say that all the span
elements are items of the grid container you created.
Tracks
Grid tracks refer to the columns and rows in a layout. Those two concepts are not new for someone that has been building grid-based layouts, so let's see how to define them in CSS Grid.
In the example above you see that we are using the properties grid-template-columns
and grid-template-rows
to define how we want our columns and rows to appear in our layout. Each value passed for those properties represent the size of the columns and rows we are creating.
For this example, we are defining 3 columns and 1 row, being that the first and last columns will have a width of 1fr
(explained in the next section) and the middle one will have the double of that: 2fr
. For the rows, we are specifically defining only 1 row, but as there are more items to be placed in the grid, new rows are automatically created for us. The first row has a fixed height of 10rem
and all the remaining rows will have equal height which is equivalent to 1fr
.
Fraction unit
The fraction unit or fr
, represents parts of the available space you have in your column or row. If you look back at the example above you'll see that for the first row we are creating a fixed height and then for each of the remaining ones we are letting them take one fraction of the space available. Basically, the height that was left in the container will be equally split into the number of rows we still have in the grid.
It is interesting to notice here that you not always have to define all of your columns or rows manually. In situations you have a big number of tracks, you can use the repeat
method to create track patterns, as in the example below.
Here we are creating a pattern for the columns. Every two columns in our grid will have a width of 1fr
for the first column and 2fr
for the second. The same works for rows as well. I recommend you to open that example in codepen and play with more combinations :)
Lines
You can also position your items based on linen numbers. When you create a CSS Grid layout you have the option to specify in which line your item will start and end. See the example below.
You can notice that in the example we are using line numbers to specify where several items will be positioned. For instance, the second span
in the grid will be horizontally positioned from line 2 to line 5 (you can use the red lines as a reference, starting from 1 and from left to right). Also, the same span
will be vertically positioned from line 1 to 3 (start counting from top to bottom). Due to that, the third span will be automatically repositioned, since the second span
is occupying the space previously reserved to span #3. Also, notice that you can use the shorthand property grid-column
or grid-row
to set the starting and ending line of an element in the same rule. Check how the span
s #5 and #6 are being positioned and play with it :)
Cell
In a grid layout, a cell is every individual space where you can lay your items on. Basically, you can lay an item in a specific cell or throughout a group of cells, by specifying the starting and ending point of an item (as we did in the previous section) or using a grid area.
Area
A grid area defines a named block that can be used to lay items in a grid template area. Let's see exactly how that works.
In this example we are defining a grid template area with the following blocks: header, sidebar, main, and footer. When you use the grid-template-area
you can specify the rows and columns you want by using the names you used for each block.
After defining the template area you have to link those block names to each element in your markup. We do that by using the grid-area
property, as shown in the example above. Once you assigned each block to a specific location in the template area, you can play around with moving the lines in the grid-template-area
property and see that you don't have to reorder your markup in order to move items around. It simply works!
One interesting thing is that if you want to add some empty blocks in your template area you can do that by using a dot in the place of any block name. See example below.
Gap
It is generally good to provide some gap between your items. You could do that using margins around your items but in CSS Grid there is a much better way to do that. Using the grid-gap
property.
CSS Grid vs Flexbox
After a bunch of new concepts and lingo in only one post, you may be wondering now what are the real advantages of CSS Grid over the previous approaches we have and are familiar with, like Flexbox.
One important difference between these two technologies is that with Flexbox you have to work with one-dimensional layouts, so you always need to think about your layout either as rows or columns at a specific time. With CSS Grid, you can work in a two-dimensional way, which means you can work with columns and rows at the same time! :)
For me, the main reason for such enthusiasm about CSS Grid is that now we can write much cleaner markups. A markup that truly tells you what are the real elements that you see in the page and does not make you create extra div
s or whichever other HTML tags you might have used for the sole purpose of layout.
Take a look at these two examples created using CSS Grid and Flexbox, respectively.
CSS Grid
Flexbox
If you look at the HTML and CSS for those two examples, you will notice that the markup for Flexbox does not look as appealing as the one for CSS Grid. You can see that extra blocks had to be created in order to position more complicated parts of the layout. As for CSS Grid, no extra blocks were needed and all the markup you have is real content the user sees in the page.
Conclusion
So if you still have that question "Why CSS Grid?", here are a few points I would like to list for you:
- cleaner markups
- increase of maintainability and flexibility for your layouts
- easy to achieve more complicated layouts as you can work with columns and rows simultaneously
- the current support is at 84.9% of the global website traffic, so it is definitely okay. You will not need a lot of fallbacks (depending on the project requirements of course).
That's it for now! Thanks for reading and let me know what you think about CSS Grid and whether you are already using it in production or not :)
Useful links
- Codepen collection used in this post
- The story of CSS Grid from its creators
- Creating CSS Grid - The Microsoft Edge Dev Show
- Grid by Example - Rachel Andrew
- CSS Grid: Moving From CSS Frameworks To CSS Grid (2018 and beyond) - Daniel Koskinen
- CSS Grid Changes EVERYTHING - Morten Rand-Hendriksen
- Grid fallbacks and overrides
Top comments (20)
Instead of thinking of Grid vs Flexbox, think in terms of Grid + Flexbox. Use grid for the global page layout and use flexbox for smaller localized areas. This gives you the best of both worlds. That being said, Grid is absolutely wonderful and you should definitely start using it when possible.
Hey Patrick, you are right! Both CSS Grid and Flexbox have their advantages and use cases. Trying to get the most out of those two technologies it's surely something to bear in mind. Thanks for pointing that out ;)
I think Grid is a great CSS feature, really easy to learn and use, but I don't think the 85% support means it's okay. My phone running ios 9 doesn't support the grid system, for example, and I have many other friends that haven't updated from that version. Because of this, I can't really test websites I made with CSS grid on my phone, and that's a huge drawback for me.
Hey Buğra, I understand the current support for CSS Grid is not something like the support we have for Flexbox for instance, which is ~94%, but for me, all the great advantages CSS Grid has to offer, make me a huge supporter, even if I have to add a couple of fallback rules for cases like yours. Also, the support it's growing really fast so if you still think the ~85% is a no-go, make sure to keep checking the support periodically ;)
Insert this link for fallback rules on the article, it is very useful and can change the decision about using or not CSS Grid. Thank you for the tips, you changed my mind about css grid.
I'm glad to hear that! And thanks for the suggestion, will do that :)
Such a good and clear explanation! I will definitely try this out at work tomorrow! I have my first project at work as an intern front end developer and I hadn't worked with grid just yet so this is awesome, thanks man !
Thanks for the feedback! I'm sure you'll have fun playing with it. Let us know how it goes :)
I used it today and it was fun! The site is not quite responsive so I'll have to figure that out at some point but I enjoyed css grid to easily devide the main with the sidebar. Before reading this I was quite worried about how I was going to make that with flex box heheh.
Nice! Try using
grid-template-areas
to easily reorder your layout components when on mobile/desktop. That, together with media queries, should help you in making the site more responsive.Thanks for the article. On second example (codepen.io/willamesoares/pen/WymGGx) you say you have specified a height of
10rem
for the first row. This makes no sense to me, the code does not have any mention to a10rem
height. Maybe you updated the pen and the article is outdaded? Is there something I'm missing here, perhaps?I'm on day one of a project to make a very large Web site mobile friendly. Site has been online for over 20 years (hymntime.com/tch - check out the Portuguese section!). I'm trying to understand whether CSS grid would work for me, and have done some initial reading.
One issue I haven't seen covered is: What happens if one or more grid columns have no corresponding HTML markup?
For example, my HTML pattern has a div called "preface." It contains text in the middle, with 0, 1 or 2 images on the left & right. In pseudo-HTML, it looks like this:
div // Start of preface. This would be my grid container.
div // Optional left side image (if none, this div isn't present).
div // Text. Always present.
div // Optional right side image (if none, this div isn't present).
div // End of preface
To avoid changing markup in over 10,000 Web pages, I'd like to define a single grid for my preface div, with 1 row & 3 columns.
But what does the browser do if the CSS defines 3 columns, but the HTML markup only has 2 columns? Or 1 column? Does this cause an error? Or is the missing column ignored & doesn't take up any screen real estate (as if it was display:none)?
Hello Dick,
Thanks for reaching out. Sorry for the delay in answering you.
So, I went through your question and for the scenario you gave me, the markup for the column that is not rendered will not take any space, which makes total sense. So if you define that the grid should start from left to right and let's say the first column is not rendered, then the second column will take the space that was supposed to be allocated to the first column.
Check this out codepen.io/anon/pen/oKvKYV
You can try to remove the first and/or third inner div in there and see what happens :)
I noticed that the content of the grid items causes them to grow larger or smaller in comparison. In your last two examples, the 'Main Content' section and the 'Posts' sections are different sizes, even though they are each 1x1 grid items. That seems counterintuitive. Is there a simple fix for that?
I found a great answer.
Awesome article! I use Grid for layouts and flexbox for content within those layouts, though sometimes nesting a grid makes more sense. To overcome the lack of browser support I serve my mobile view inside of
@supports not
tags.I still could not understand difference between
justify-content
andalign-content
Check this medium.freecodecamp.org/the-comple...
As a non-webdeveloper, this was quite a sweet read :p
What a clean, concise and detailed explanation of grid's overall concept, main features, and competitive space. Thanks for putting this together. Definitely smashing that follow button for your posts.