Difference between Flexbox and Grid
Flexbox – one dimensional. It aligns content and distributes space along a single axis, either a row or a column.
Grid – two dimensional. Lets you control the sizing, positioning, and spacing of rows and columns at the same time. When you declare a grid both the main and cross axes are defined.
Two Most Important Elements
- Grid Containers
- the first step is to declare the grid container, which is similar with Flexbox.
- establishes the grid formatting context
- manages how its direct child elements are spaced, sized and aligned
- Grid Items
- the direct children of a grid container
- there can be any number of grid items inside a grid container
Once you’ve established the grid formatting context, you can start positioning and aligning content into a grid. And the grid is formed by an intersecting set of horizontal and vertical lines called grid lines.
Grid lines – intersecting set of horizontal and vertical lines. It divide the grid container into columns and rows, or the areas into which grid items are aligned, sized and placed.
Defining the Grid
display: grid;
declares grid container
.grid {
max-width: 800px; /*set maximum width size*/
display: grid; /*defines grid value*/
}
Grid Tracks – The space between two adjacent grid lines (the columns and the rows of the grid.)
grid-template-columns: ;
– to set the column tracks
grid-template-rows: ;
– to set the row tracks
These properties are declared in the grid container, and both properties above specify the size of each grid track.
What I learned here – defining the grid-template-columns: ;
will set the number and size of columns, regardless of the items defined on the HTML file. Therefore, the number of rows will be dependent on the number of items and number of columns set. For example, having 3 columns with 6 items will create two rows. The grid-template-rows: ;
will set the size in terms of height of the grid items.
Note: A grid item can also be a grid container.
Grid Gutters
grid-column-gap: 20px;
grid-row-gap: 15px;
or
grid-gap: 15px 20px;
This only adds gap in between items, not at the beginning and end.
Grid Lines
Grid lines can be defined by numerical value. Note that this is not the number of columns/row. Grid line 1 and 2 creates the first column, and so on.
fr or Fraction unit
A flexible length unit designed for creating grid tracks that expand and contract based on the free space in the grid.
grid-template-columns: 1fr 1fr 1fr;
This creates 3 flexible columns.
repeat() Notation
grid-template-columns: 1fr 1fr 1fr;
/*this can be writted as */
grid-template-columns: repeat(3, 1fr);
/* it can also be combined */
grid-template-columns: 2fr 1fr 1fr 1fr;
/* this can be written as */
grid-template-columns: 2fr repeat(3, 1fr);
Leave a Reply