To use CSS Grid set the display property of the container element to grid.
.container {
display: 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.
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.
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.
.container {
display:grid;
grid-template-columns: 300px 300px 300px;
grid-template-rows: 250px 600px;
grid-template-areas:
"hd hd hd hd hd hd hd hd"
"sd sd sd main main main main main"
"ft ft ft ft ft ft ft ft";
}
.header {
grid-area: hd;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Exercise 1</title>
<meta
content="width=device-width, initial-scale=1, maximum-scale=1"
name="viewport"
/>
<style>
.container{
/* Step 1: Set display to grid */
display:grid;
width: 80vw;
height: 100vh;
margin: auto;
/* Step 2: setup rows amd columns */
/* grid-template-columns: repeat(3, 1fr); */
grid-template-columns: 100px ;
grid-template-rows: 250px 600px 100px;
grid-template-areas:
"hd hd hd hd hd hd hd hd"
"sd main main main main main main main"
"ft ft ft ft ft ft ft ft";
border: 2px solid yellow;
}
.box{
border: 1px solid red;
background: #F8FA9D;
}
/* Assign grid area below */
.header{
grid-area: hd;
}
.footer{
grid-area: ft;
}
.sidebar{
grid-area: sd;
}
.content{
grid-area: main;
}
</style>
</head>
<body>
<div class = "container">
<div class="header box">Header</div>
<div class="sidebar box">Sidebar</div>
<div class="content box">Content</div>
<div class="footer box">Footer</div>
</div>
</body>
</html>