skip to Main Content

I have a grid parent that has rows. Rows has two children. The first child’s width is unknown. I want to set auto column width. I can achieve this with this:

.list {
    display: grid;
    grid-template-columns: auto 1fr;
    gap: 1rem;
}
<div class="list">
  <span>First Child</span>
  <span>Second Child</span>

  <span>First</span>
  <span>Second Child</span>

  <span>Long Text Child</span>
  <span>Second Child</span>
</div>

But I need a container element for the rows and I couldn’t achieve the result as above:

.list {
  display: grid;
  gap: 1rem;
}

.row {
  display: grid;
  grid-template-columns: auto 1fr;
  gap: 1rem;
}
<div class="list">
  <div class="row">
    <span>First Child</span>
    <span>Second Child</span>
  </div>
  
  <div class="row">
    <span>First</span>
    <span>Second Child</span>
  </div>
  
  <div class="row">
    <span>Long Text Child</span>
    <span>Second Child</span>
  </div>
</div>

2

Answers


  1. You can "open" the rows with display: contents like so.

    One downside, it treats the row wrappers as though they were not there so if you wanted additional styling for the rows that might be problematical.

    .list {
      display: grid;
      grid-template-columns: auto 1fr;
      gap: 1rem;
    }
    
    .row {
      display: contents;
    }
    
    span {
      outline: 1px solid grey;
    }
    <div class="list">
      <div class="row">
        <span>First Child</span>
        <span>Second Child</span>
      </div>
    
      <div class="row">
        <span>First</span>
        <span>Second Child</span>
      </div>
    
      <div class="row">
        <span>Long Text Child</span>
        <span>Second Child</span>
      </div>
    </div>
    Login or Signup to reply.
  2. A subgrid can be used to make the size of .row column tracks the same as of the parent grid.

    The row should span all columns defined in the parent.

    .list {
      display: grid;
      grid-template-columns: auto 1fr;
      gap: 1rem;
    }
    
    .row {
      display: grid;
      grid-template-columns: subgrid;
      grid-column: span 2;
    }
    <div class="list">
      <div class="row">
        <span>First Child</span>
        <span>Second Child</span>
      </div>
    
      <div class="row">
        <span>First</span>
        <span>Second Child</span>
      </div>
    
      <div class="row">
        <span>Long Text Child</span>
        <span>Second Child</span>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search