CSS: Grid Layout
What is grid layout
Grid Layout is layout system that creates layout based on rectangular grid, in a flexable and dynamic way.
First you set a element's display property to display: grid.
then you define the lengths between vertical grid lines (columns) and horizontal grid lines (rows), by using grid-template-columns and grid-template-rows. This gives you a grid of lines that is the foundation of your layout.
Then you define how child items fill the cells or areas (neighboring cells) between grid lines, by using grid-row, grid-column or grid-area. A child item may occupy more than one grid cells.
here's a typical grid layout for website home page:
the complete code is:
<div class="xgrid-main-RrpYB"> <div class="header">header</div> <div class="main">main. good morn.</div> <div class="sidebar">sidebar</div> <div class="footer">footer</div> </div>
.xgrid-main-RrpYB { display: grid; grid-template-columns: 1fr 4fr; grid-template-rows: auto auto auto; margin: 15px; gap: 1px; grid-template-areas: "a a" "b c" "d d"; > * { border: solid 2px silver; } > .main { grid-area: c; height: 60px; } > .header { grid-area: a; } > .sidebar { grid-area: b; } > .footer { grid-area: d; } }
The grid container
To create a grid layout, set a element's Display Property to display: grid or display: inline-grid.
Its direct children are grid items. They are the contents of the grid.
example
by default, items are made into rows.
<div class="xgrid-nil54"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> </div>
.xgrid-nil54 { display: grid; > div { border: solid 1px grey; } }
Define grid shape
Define child item position and span.
Implicit grid
- The row count, is the number of values in
grid-template-rows - The column count, is the number of values in
grid-template-rows
Total number of explicit grid cells is equal to row count times column count.
extra items become rows
if you have more items than your explicit grid cells, the extra items become rows by default, and is called implicit grid.
<div class="xgrid-extra-kFNk4"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5 extra</div> <div>6 extra</div> </div>
.xgrid-extra-kFNk4 { display: grid; grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr; > div { border: solid 1px grey; } }
Browser support
supported by all major browsers since 2017.
CSS grid layout
- CSS: Grid Layout
- CSS: grid-template-columns
- CSS: grid-template-rows
- CSS: grid repeat() function
- CSS: grid-row, grid-column (grid item position and span)
- CSS: grid-area
- CSS: grid-template-areas
- CSS: gap, row-gap, column-gap (flex, grid)
- CSS: justify-content
- CSS: justify-items (grid)
- CSS: justify-self (grid)
- CSS: align-items (flex cross axis)
- CSS: align-self (for flex items)