Lesson 4: CSS Grid
An Example of Grid vs Flexbox
To use CSS Grid set the display
property of the container element to grid
.
Recap
CSS Grid v. Flexbox
Grid is two dimensional, while Flex is one
Grid is layout first, while Flexbox is content first
Flex is for components of an app, Grid is for the app layout itself
CSS Grid does not replace Flexbox. Each can achieve things that the other is not capable of, and in fact, a true master can use Flexbox and CSS Grid together in harmony to create the ultimate webpage layout.
At the highest level CSS Grid excels at creating layouts for a webpage, while Flexbox is a master of content flow for each element that makes up the page layout.
Rows & Columns
After setting the display property of your container div to grid, the next step is to set the rows and columns in your grid which can be done with the CSS properties:
grid-template-columns
grid-template-rows
And to define gutters between rows and columns you can use the property grid-gap
on the parent container that has the display
property set to grid
.
Rows & Columns in Action
利用grid-template-columns和grid-template-rows來定義切割的空間。
範例:Add a grid
to the container
in index.html
. In creating the grid
, use a number of columns and/or rows that changes the default layout.
Generated code:
Reference
CSS Grid Layout: The Fr Unit (fr = fraction)
Grid Areas
空間切割完了之後,就可以利用座標的方式來指定位置。
The grid-area
property specifies a particular area or set of rows and columns that a grid item occupies. It is applied to the grid item itself with CSS. Here is an example:
Grid Tracks
定義區塊為兩條線之間的區域
We define rows and columns on our grid with the grid-template-columns
and grid-template-rows
properties. These define grid tracks. A grid track is the space between any two lines on the grid.
Grid lines
線的定義
Becausegrid-area
is shorthand for the properties: grid-row-start
, grid-column-start
, grid-row-end
and grid-column-end
, the code above places the item from rows 1-3, and columns 2-3.
空間切割完了之後,也可以給空間名稱來指定位置。
Named grid space(Named spaces)
Track listings with
repeat()
notationTrack sizing and
minmax()
Further Research
For even more control over how your content is laid out, check out this article titled How Items Flow Into a CSS Grid.
Last updated