Tag: Grid-Column-Span

HTML5 Series - Grid

There was a time when an HTML page layout mainly consisted of tables, and lots of them. Tables went inside other tables and complex layouts were achieved through the use of colspans and rowspans. The only problem though was it was a mess.

By using tables the HTML mark-up was dictating the design/layout of the page and if you ever wanted to change anything it was a huge task to undertake. Since then the world has moved on and now most webpages consist mainly of div's. But what if you did want to quite a rigid layout with columns and rows?

HTML5 introduces the Grid style through CSS. Your page can still consist mainly of div's (or anything for that matter), but in your css you set a display property of grid (for now in IE it's -ms-grid). You can then specify a grid-columns and grid-rows property to create a grid within your div.

Child items can be placed in grid cells through grid-row and grid-column properties in the CSS, and if you want something to span more than one cell you can use grid-row-span or grid-column-span.

If you've done any XMAL programming (WPF/Silverlight/Win8/Windows Phone) then this should all sound very similar to XMAL's Grid control.

The example below creates something like this:

1<style>
2 /* Set a grid with 3 columns and 2 rows */
3 div {
4 display: -ms-grid;
5 -ms-grid-columns:200px 200px 200px;
6 -ms-grid-rows:200px 200px;
7 }
8
9 /* Position the child div's in the grid */
10 div:nth-child(1) {
11 -ms-grid-row: 1;
12 -ms-grid-column: 1;
13 }
14 div:nth-child(2) {
15 -ms-grid-row: 2;
16 -ms-grid-column: 1;
17 }
18 div:nth-child(3) {
19 -ms-grid-row: 1;
20 -ms-grid-column: 2;
21 -ms-grid-row-span:2; /* The middle cell spans 2 rows */
22 }
23 div:nth-child(4) {
24 -ms-grid-row: 1;
25 -ms-grid-column: 3;
26 }
27 div:nth-child(5) {
28 -ms-grid-row: 2;
29 -ms-grid-column: 3;
30 }
31
32 /* Add a border to the cells */
33 div>div {
34 border: solid 1px black;
35 }
36</style>
37<div class="myGrid">
38 <div></div>
39 <div></div>
40 <div></div>
41 <div></div>
42 <div></div>
43</div>

It's also worth noting that the column/row sizes can be specified using fractions rather than fixed sizes. e.g. The following will produce a grid 600px wide where the middle column is twice the width of the other 2.

1<style>
2 /* Set a grid with 3 columns and 2 rows */
3 div {
4 display: -ms-grid;
5 width:600px;
6 -ms-grid-columns:1fr 2fr 1fr;
7 -ms-grid-rows:200px 200px;
8 }
9</style>

For another great example check out this hands on page from Microsoft Hands on: CSS3 Grid