How do I use css grid names instead of grid line numbers?



  • In article How do I create a template web page layout using css grid? we saw how to create a basic template for a web page, we used CSS grid line numbers.

    We can also use names instead of grid line numbers.

    First we decide what to name the grid row lines in our container Instead of using the following:

    ...
     .container {
            width: 800px;
            height: 500px;
            background-color: chocolate;
            margin: auto;
            display: grid;
            grid-template-rows: 1fr 1fr 1fr 1fr 1fr;
            grid-template-columns: 1fr 1fr 1fr 1fr;
            grid-gap: 1rem;
          }
    ...
    

    We replace it with this. Using square brackets to enclose the name. We need to define where the row starts and ends.

    
    ...
    .container {
            width: 800px;
            height: 500px;
            background-color: chocolate;
            margin: auto;
            display: grid;
            grid-template-rows: [header-start] 1fr [header-end main-start] 1fr 1fr [main-end box-start] 1fr [box-end footer-start] 1fr [footer-end];
            grid-template-columns: 1fr 1fr 1fr 1fr;
            grid-gap: 1rem;
          }
    ...
    

    In some places the end of one section is the start of another so the two names are put within the same square brackets.

    After defining these they can be used instead of the grid row numbers. For example:

    ...
          .header {
            grid-column: 1 / 5;
            grid-row: header-start / header-end;
          }
    
          .sidebar {
            grid-column: 1 / 2;
            grid-row: main-start / box-end;
          }
    ...
    

    The sidebar section spans the main section through to the end of the box section so individual names are not define for the sidebar.

    In a similar way we can name the columns, replace the following:

    ...
            grid-template-columns: 1fr 1fr 1fr 1fr;
    ...
    

    With this code, using the short form to define the fractional units.

    ...
            grid-template-columns: repeat(4, [col-start] 1fr [col-end]);
    ...
    

    After doing this [col-start] and [col-end] can be used for example:

    ...
          .header {
            grid-column: col-start 1 / col-end -1;
            grid-row: header-start / header-end;
          }
    
          .sidebar {
            grid-column: col-start 1 / col-end 1;
            grid-row: main-start / box-end;
          }
    ...
    

Log in to reply
 

© Lightnetics 2024