2021-10-12
Positioning and laying out elements on a page used to be tricky. We had to use floats, inline-blocks, or even tables to get things in the right place. Now with Flexbox and Grid, CSS layout has become much more straightforward.
Flexbox is designed for one-dimensional layout, meaning it works in a single direction at a time, either in a row or in a column. To start using Flexbox, we set display: flex on the parent container.
.container {
display: flex;
justify-content: center;
align-items: center;
}justify-content controls the alignment along the main axis (horizontal if the direction is row), and align-items controls the alignment along the cross axis (vertical if the direction is row).
Some useful values for justify-content are flex-start, flex-end, center, space-between, and space-around. The space-between distributes items evenly with the first item at the start and the last item at the end. The space-around gives equal spacing around each item.
For the children elements, we can use flex-grow to control how much space each child should take. For example, if we have three children and we set flex-grow: 1 on all of them, they will share the available space equally. If we set flex-grow: 2 on the second child, it will take twice as much space as the others.
Grid is designed for two-dimensional layout. It works with both rows and columns at the same time. To start using Grid, we set display: grid on the parent container.
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
grid-gap: 16px;
}The grid-template-columns defines how many columns we want and how wide each column should be. The fr unit stands for fraction, so 1fr 1fr 1fr means three columns with equal width. We can also mix units like 200px 1fr 1fr where the first column is fixed at 200px and the remaining two share the rest of the space equally.
For responsive layouts, we can use repeat and minmax together:
.container {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 16px;
}This will automatically create as many columns as can fit, with each column being at least 250px wide. When the screen gets smaller, the number of columns will reduce automatically.
I usually use Flexbox for smaller components like navigation bars, card layouts in a single row, or centering content inside a container. Grid works better for the overall page layout or when I need to control both rows and columns at the same time, like a dashboard with multiple sections.
Both of them can be combined. For example, we can use Grid for the page layout and then use Flexbox inside each grid cell to arrange the content within that cell.