0

I had a problem making an responsive width of element that attributed with display:table-cell or element <td> itself, i have a parent element <div class="parent"> with few child written below

<div class="parent">
    <div class="child"></div>
    <div class="child"></div>
    <div class="child"></div>
</div>

And written few lines of css codes like below

.parent {
    display: table;
    width: 100%;
    border-collapse: collapse;
}
.parent .child {
    display: table-cell;
    width : 100%;
    padding: 5px;
}

The problem is, the first child will have 100% of parent width, which the other two got 0% width, i try to devide and change the css codes like this

.parent .child {
    display: table-cell;
    width : 33%;
    padding: 5px;
}

It did work fine, but the things that i really want is to devide the width of the parent dinamicly, depending of the amount of the child, i mean it's not staticly like that, sometimes 3 sometimes 5 and etc.

Maybe i can count the amount of the child using js elementParent.childElementCount and devide the 100% by the amount of the child to give into each other child width using JavaScript, but how if i only using css?

Thanks for any correction.

Irvan Hilmi
  • 378
  • 1
  • 4
  • 16

2 Answers2

0

You can apply width as in child div 'auto'

 .parent .child {
      display: table-cell;
      width : auto;
      padding: 5px;
                }

Let me know if this meets your requirement

0

Add the following:

.parent {
    ...
  table-layout: fixed;
}
.parent .child {
    ...
  overflow-x: hidden;
  word-break: break-word;
}

This combination makes the "table" distribute the widths of each "cell" evenly. Added to the demo is some JavaScript that adds extra cells to demonstrate the behavior previously described.


Demo

document.querySelector('button').onclick = addCell;

function addCell(e) {
  var table = document.querySelector('.parent');
  table.insertAdjacentHTML('beforeend', `
    <div class="child">XX</div>`);
}
.parent {
  display: table;
  width: 100%;
  border-collapse: collapse;
  border: 1px solid grey;
  table-layout: fixed;
}

.parent .child {
  display: table-cell;
  padding: 5px;
  border: 1px solid black;
  overflow-x: hidden;
  word-break: break-word;
}

button {
  float: right
}
<div class="parent">
  <div class="child">XXXXXXXXXXXXXXXXXXX</div>
  <div class="child">XX</div>
  <div class="child">XX</div>
</div>

<button>Add Cell</button>
zer00ne
  • 41,936
  • 6
  • 41
  • 68