With the new W3C specification, you can now use CSS to create a grid layout on your webpages. Previously, HTML tables were often used to create grids, but with the increasing popularity of mobile devices, this is no longer considered best practice because tables aren’t responsive at all. Divs are commonly used to create a grid-like structure, but this new W3C grid specification is meant to allow developers to create responsive grids natively using CSS.
The grid specification works similarly to flexbox in that you have to set a div or a container to display as a grid, like this:
- display: grid;
You’ll then need to define the sizes for the columns and the rows using grid-template-columns and grid-template-rows properties:
- grid-template-rows: 20px 30px 20px 30px;
- grid-template-columns: 100px 100px 100px;
The code above creates 4 rows (the first has a height of 20px, the second a height of 30px, the third a height of 20px, and the fourth 30px), and 3 columns (each of which are 100px wide). By looking at the code above, you can see the simple way in which the syntax works to create your basic grid. The rows and columns property also take % values and the “auto” value.
With the CSS grid display, you can also use your stylesheets to give specific names to different lines within your grid, or to set a designated header, footer, sidebar, or main content area. The CSS grid property is still new and experimental, and probably isn’t practical to start using widely, but if you do use it make sure you remember to use your appropriate vendor prefixes for cross-browser compatibility. Read more about the CSS grid property here.