课程: CSS: Advanced Layouts with Grid
When to use Grid?
- [Instructor] CSS gives us a lot of layout options for the web, though grid is the most powerful method we have. That said, allow me to give you a quick overview of the CSS flexbox layout module as compared to grid, and when you might choose to use one over the other, or even use a combination of both. For starters, flexbox is a one-dimensional layout, meaning you can either create a row or a column along a single axis. If you want to create the appearance of additional rows or columns, that could be done by wrapping flex items along that same axis, but it's not a true grid. If you need to work with both rows and columns at the same time, grid is the better option. With both flexbox and grid we get the ability to order elements within the container however we want, so source order doesn't necessarily have to match the display order. This is a powerful feature of both, but can create some accessibility issues if you're not careful. More on that in another lesson. Flexbox is considered content-first or inside out, whereas grid is considered layout first or outside in. What do I mean by that? With flexbox, we're arranging items along a single axis, and the size and distribution of the items is primarily determined by the content itself. Grid, on the other hand, describes a grid structure with rows and columns, so the outside container, if you will, and then content is placed within that. As such, this makes Flexbox well suited for simple layouts when you're not sure exactly what your content will be, or components such as navigation bars, where you're wanting to distribute items along that single axis. Grid, on the other hand, is perfect for more complex layouts with multiple rows and columns, and when you need to position elements precisely. Grid and flexbox are meant to be used together as well. For example, you might use Grid for an overall site layout, but use Flexbox for the navigation. Or you could lay out cards on a Grid, but use flexbox to arrange the items within each individual card. Really, the approach you take will be determined by the needs of your layout, the content you're working with, and the spatial relationship you need to establish between items on the page. As we work through examples in this course, and you take time to experiment, you'll get a good feel for when you might choose grid, flexbox, or even a combination of the two.