Search code examples
htmlcsscss-grid

How to make a CSS grid item match parent's height like a flexbox item does


I have this simple setup:

<div class="grid-container">
  <div class="grid-child-1">
    <div class="content">
      some long text<br/> here in the child number<br/> 2 some long text<br/> here in the child number 2 some<br/>
      long text here<br/> in the child number some long<br/> text here in the child number 2 some long<br/>
      text here in the<br/> child number 2 some long<br/> text here in the child number<br/> 2 ывавыа ваss<br/>
      text here in the<br/> child number 2 some long<br/> text here in the child number<br/> 2 ывавыа ваss<br/>
    </div>
  </div>
  <div class="grid-child-2">some text</div>
</div>

and styles:

  </style>
      .grid-container {
          display: grid;
          grid-template-columns: 1fr 1fr;
          border: 1px solid;
          width: 100%;
          height: 200px;
      }
  </style>

With this setup, the grid-child-1 item stretches beyond the parent's 200px height:

enter image description here

How to make it stretch only as far as the parent's height goes. Similar to flexbox:

enter image description here


Solution

  • You could define the row height in the template:

    E.g. grid-template: 100% / 1fr 1fr; in place of grid-template-columns: 1fr 1fr;

    #id {
     height: 300px;
    }
    
    .grid-container {
          display: grid;
          grid-template: 100% / 1fr 1fr;
          border: 1px solid;
          width: 100%;
          height: 200px;    
    }
          
    .grid-child-1 {
        background-color: red;
    }
    <div id="outer-container">
     <div class="grid-container">
      <div class="grid-child-1">
        <div class="content">
          some long text<br/> here in the child number<br/> 2 some long text<br/> here in the child number 2 some<br/>
          long text here<br/> in the child number some long<br/> text here in the child number 2 some long<br/>
          text here in the<br/> child number 2 some long<br/> text here in the child number<br/> 2 ывавыа ваss<br/>
          text here in the<br/> child number 2 some long<br/> text here in the child number<br/> 2 ывавыа ваss<br/>
        </div>
      </div>
      <div class="grid-child-2">TEST</div>
     </div>
    </div>

    It's also worthwhile to point out, per this answer and the specification, that:

    If you have not set an explicit height to the containing block (and the child is not absolutely positioned), then your child element with percentage height will have nothing to go on and height will be determined by content and other properties.

    Thanks to @MichaelBenjamin for prompting.