Search code examples
cssgrid-layoutcss-grid

Set css grid child element's size on the grid, without specifying what column or row it should go into


Is it possible do set a div's height and width in amount of rows/columns they should span, without specifying exactly which columns or rows they should go into?

For example, if I have two classes, say .long and .wide, and I want the .long class to be 3 rows high, and 1 column wide, and the .wide class be 3 columns wide but only 1 row high.

My specific use case involves Angular 5, I'm dynamically loading in objects and would like to make some of them larger than others. I know I could do this using flexboxes and setting the height, but was curious to see if I could achieve the same (much neater) with a grid, but all I've been finding has every class specified with grid-column: x/y; grid-row: a/b and the like.


Solution

  • There is an alternative syntax for grid-row and grid-column that sets a span:

    .grid {
        display: grid;
        border: solid 1px black;
        grid-auto-rows: 30px;
        grid-auto-columns: repeat (5, 50px);
        grid-gap: 5px;
    }
    
    .grid div {
        background-color: lightgreen;
    }
    
    .wide {
        grid-column: span 3;
    }
    
    .long {
        grid-row: span 3;
    }
    <div class="grid">
    <div></div>
    <div class="long">LONG</div>
    <div class="wide">WIDE</div>
    </div>