Flexbox vs. Grid?
Should you use Flexbox or Grid? What are the big differences, and when do each work best? In the world of CSS, these are all important questions. To start off, Grid was mostly invented to do things that Flexbox can’t do. It isn’t a replacement for Flexbox, that’s an important point, Flexbox is still a great tool to have in your CSS tool belt. In fact, it’s a necessary tool. There are plenty of things that Flexbox can do that Grid can not. The entire flow of the page is still best controlled by Flexbox. Grid best comes in when we are designing specific parts of the page. Grid handles the layout for a particular container. A single container on the page, including the elements that are a child of that container.
One key difference between the two is the direction of the CSS calculations that each control.
Flexbox is used when you want to line things up in one direction, making it one-dimensional. Think of it as a whole bunch of boxes that are in a long line that if needed will wrap below. Flexbox only thinks about one direction and makes the CSS calculations specific to those boxes in that one direction. Flexbox doesn’t have any way to tell the page to start making changes in the other direction. That’s where Grid comes in. Grid has the ability to line things up in two directions, which makes it two-dimensional. Grid will always be looking to make calculations in two directions. It has the ability to think about rows and columns at the same time, Here is a diagram of a layout that uses Grid, notice the CSS lining up the boxes in both directions.
Now with Flexbox, the calculations are being done in each row, it has no ability to line up the columns, which would require it to be thinking about multiple rows.
One key thing that Grid can do that Flexbox cannot do is intentionally overlap items. If your website design is going to require some overlap of specific elements, Grid is going to have to be used.
So how do we define Grid in our CSS? Let’s say we will be using Grid to style our header. To start we attach the display property of grid to the container we are styling ( In this case the header).
.header{
display:grid
}
Once we’ve done that we will then define the style and size of the rows and columns that make up our grid.
.header {
grid-template-columns: 75px 50px 25px;
grid-template-rows: 25px 50px 75px;
}
The final step is to then define the amount of rows and columns that we will need. We use the terms, grid-row-start, grid-row-end, grid-column-start, and grid-column-end.
.header {
grid-column-start: 1;
grid-column-end: 3;
grid-row-start: 1;
grid-row-end: 4;
}
To recap, Should you use Flexbox or Grid, well it’s going to come down to how you want to style your page, and oftentimes you’ll find yourself needing to use both. Like I mentioned at the start, Grid in no way replaces Flexbox, it’s simply another tool to use. Happy coding everyone!