Difference between revisions of "CSS Grid"
VKranendonk (talk | contribs) |
VKranendonk (talk | contribs) |
||
Line 28: | Line 28: | ||
</source> | </source> | ||
We also have to create columns and or rows. We can do this with the properties {{code|inline=y|lang=css|grid-template-columns}} and {{code|inline=y|lang=css|grid-template-rows}}. | |||
You set the amount of columns by adding or removing | You can set the amount of columns by adding or removing values. | ||
For example {{code|inline=y|lang=css|grid-template-columns: 200px 200px}} will | For example {{code|inline=y|lang=css|grid-template-columns: 200px 200px}} will create two columns of each 200 pixels width. {{code|inline=y|lang=css|grid-template-columns: 300px 500px 300px}} will create 3 columns, the first and last 300 pixels wide, the middle columns 500 pixels wide. | ||
<source lang="html5"> | <source lang="html5"> |
Revision as of 08:39, 5 September 2022
In CSS land there are multiple ways of positioning elements. The most common methods are absolute positioning
, Flexbox position: absolute;
and CSS grid display: flex;
.
display: grid;
This article will describe how to create a layout with CSS Grid.
CSS grid places its direct children onto a "grid". In the following HTML snippet the parent element has the class 'grid-container' and 6 children.
<div class="grid-container">
<div>Grid item 1</div>
<div>Grid item 2</div>
<div>Grid item 3</div>
<div>Grid item 4</div>
<div>Grid item 5</div>
<div>Grid item 6</div>
</div>
We first have to set the parent element to be displayed as a grid via the CSS property "display".
<style>
.grid-container {
display: grid;
}
</style>
We also have to create columns and or rows. We can do this with the properties
and grid-template-columns
.
grid-template-rows
You can set the amount of columns by adding or removing values.
For example
will create two columns of each 200 pixels width. grid-template-columns: 200px 200px
will create 3 columns, the first and last 300 pixels wide, the middle columns 500 pixels wide.
grid-template-columns: 300px 500px 300px
<style>
.grid-container {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 300px 300px;
}
</style>
The following code creates a grid of 3 columns, each column 200px wide and 2 rows of 300px height.
<div class="grid-container">
<div>Grid item 1</div>
<div>Grid item 2</div>
<div>Grid item 3</div>
<div>Grid item 4</div>
<div>Grid item 5</div>
<div>Grid item 6</div>
</div>
<style>
.grid-container {
display: grid;
grid-template-columns: 200px 200px 200px;
grid-template-rows: 300px 300px;
}
</style>
Resources
- CSS Grid course by Wes Bos is full-on in depth course on CSS Grid
- MDN Web Docs has a good introduction to CSS Grid
- CSS Grid Garden is a fun CSS grid game
- CSS Tricks has a good reference article on CSS Grid