0

I am working on a project where I have to render a dynamic table. Dynamic in both the number of rows and number of columns. I am using CSS grid for the table. My problem is best demonstrated with this code:

function add(type){
  var tmp = document.createElement(type)
  tmp.innerHTML='tmp'
 document.getElementById('place').insertAdjacentElement('afterend', tmp)
}

function addInput(){
  add('input')
}

function addDiv(){
  add('div')
}
 :root {
   --rowNum: 2;
   --colNum: 3;
 }
 
 .container {
  display: grid;
  grid-template-columns: 50% 50%;
  grid-template-rows: auto 40px;
 }

.table {
     grid-template-columns: 100px repeat(var(--colNum), auto);
     grid-template-rows: repeat(var(--rowNum), 50px);
     grid-column: 1;
     display: grid;
 }
 
 .empty {
     grid-column: 2;
     grid-row-start: 1;
     grid-row-end: 2;
     grid-template-columns: 1;
     display: grid;
 }


 * { background-color: rgba(255, 0, 0, 0.2); }
 * * { background-color: rgba(0, 255, 0, 0.2); }
 * * * { background-color: rgba(0, 0, 255, 0.2); }
 * * * * { background-color: rgba(255, 0, 255, 0.2); }
 * * * * * { background-color: rgba(0, 255, 255, 0.2); }
 * * * * * * { background-color: rgba(255, 255, 0, 0.2); }
 * * * * * * * { background-color: rgba(255, 0, 0, 0.2); }
 * * * * * * * * { background-color: rgba(0, 255, 0, 0.2); }
 * * * * * * * * * { background-color: rgba(0, 0, 255, 0.2); }
<div class="container">
  <div class="table" id='table'>
    <div>
      1
    </div>
    <div>
      2
    </div>
    <div id='place'>
      3
    </div>
    <div>
      4
    </div>
    <div>
      5
    </div>
    <div>
      6
    </div>
    <div>
      7
    </div>
  </div>
  <div class="empty">
    empty
  </div>
</div>

<button onclick="addDiv()">
  addDiv
</button>

<button onclick="addInput()">
  addInput
</button>

Please run the snippet and keep clicking on the addDiv button. Things work as expected, new cells are added and they wrap to the next row. Now please click on addInput three to four times; as you can see, when adding input siblings, the grid flows into the neighboring column on the parent container.

My questions are why this is happening? am I misusing something or is this a bug? Also how do get the behavior with a div while using an input? (wrapping in div doesn't work)

maininformer
  • 967
  • 2
  • 17
  • 31

1 Answers1

1

Because Inputs have an initial width (read more here) it is needed to reset these by setting the width to the 100% of its parent:

.table > * {
    width: 100%;
}

Another solution or best to work with the above together, is to prevent the cols from overflowing by setting and overflow value. The overflowing happens only because there is not enough space.

.table > * {
    overflow: hidden;
}

I would also suggest giving every child a class instead of using the asterisk (*).

muuvmuuv
  • 901
  • 2
  • 13
  • 39