skip to Main Content

I need a layout where the first column has a common max-content width across all rows, but the rows are distinct elements as I need to attach event handler to them. So far I can achieve either-or. Can I have both somehow?

for(const el of [...document.getElementsByClassName('row')]) el.onclick=e => {el.style.backgroundColor = 'red'};
.container {
  display: grid;
  grid-template-columns: max-content 1fr;
}

.row {
  display: grid;
  grid-template-columns: max-content 1fr;
  background-color: #F0F0FF;
}

.col {
  width: max-content;
}

div {
border: 1px solid red;
margin: 10px;
}
Column span
<div class="container">
    <div class="col">323232323232</div>
    <div>1</div>
    <div class="col"></div>
    <div>2</div>
    <div class="col"></div>
    <div>3</div>
</div>

Row element
<div>
  <div class="row">
    <div class="col">323232323232</div>
    <div>1</div>
  </div>
  <div class="row">
    <div class="col"></div>
    <div>2</div>
  </div>
  <div class="row">
    <div class="col"></div>
    <div>3</div>
  </div>
</div>

2

Answers


  1. Subgrid is now supported cross-browser. I think this is what you might want:

    for(const el of [...document.getElementsByClassName('row')]) el.onclick=e => {el.style.backgroundColor = 'red'}; 
    .container {
      display: grid;
      grid-template-columns: max-content 1fr;
    }
    
    .row {
      display: grid;
      grid-column: 1 / 3;
      grid-template-columns: subgrid;
      background-color: #F0F0FF;
    }
    
    .col {
      width: max-content;
    }
    
    div {
      border: 1px solid red;
      margin: 10px;
    }
    <div class="container">
      <div class="row">
        <div class="col">323232323232</div>
        <div>1</div>
      </div>
      <div class="row">
        <div class="col"></div>
        <div>2</div>
      </div>
      <div class="row">
        <div class="col"></div>
        <div>3</div>
      </div>
    </div>
    Login or Signup to reply.
  2. As someone said, what you want is table layout:

    for(const el of [...document.getElementsByClassName('row')]) el.onclick=e => {el.style.backgroundColor = 'red'};
    .container {
      display: table;
      border-spacing: 10px;
    }
    .row {
      display: table-row;
      background-color: #F0F0FF;
    }
    .row > * {
      display: table-cell;
    }
    .row > :not(.col) {
      width: 100%;
    }
    div {
      border: 1px solid red;
      margin: 10px;
    }
    <div class="container">
      <div class="row">
        <div class="col">323232323232</div>
        <div>1</div>
      </div>
      <div class="row">
        <div class="col"></div>
        <div>2</div>
      </div>
      <div class="row">
        <div class="col"></div>
        <div>3</div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search