slowpoke123 slowpoke123 - 2 months ago 10
CSS Question

Make td element same width as input element with only using css/scss?

I have tried to ask this question before without any luck so I'll try to ask it again. I really hope someone can help.

What I want is:


  • the table to stretch to 100%

  • the first input element to "fill" the table since the table has to be 100%

  • the other input elements to be in different sizes

  • the td to be the same width as the input elements (no space)

  • to achieve this with only changing the css (no js, no html changes)



In the code snippet below you can see my html table. I do not want to change it in any way, and I don't want to add any classes. I don't want to use any javascript either.

If you run the code snippet you can see my problem. The td's are much wider than the input element. I want the second, third and forth td to "shrink" to the size of the input element. I want the first td to strech out (since the table has to be 100%).



table {
width: 100%;
border-collapse: collapse;
}

td {
border: 1px solid #000;
}

.small {
width: 20px;
}

.medium {
width: 40px;
}

<table>
<tbody>
<td>
<div>
<input type="text" />
</div>
</td>
<td>
<div>
<input class="small" type="text" />
</div>
</td>
<td>
<div>
<input class="medium" type="text" />
</div>
</td>
<td>
<div>
<input class="medium" type="text" />
</div>
</td>
</tbody>
</table>





I know this can be solved by setting the width on the td elements insteadof the input, but that is not what I am asking for. I also know it can be solved by setting the width of the table to auto, but that is not what I want either. I just want the td elements to be the same width as the input elements with using css only.

Answer

Is this what you wanted to achieve? I set the first td and input to have width: 100%; so they will fill the rest of the table after all the rest of the divs are the width of the elements inside it (set by your class). With box-sizing: border-box you can set it so that borders etc have no effect on the width of the elements. You can also set box-sizing property only to table and all it's elements with table * { box-sizing: border-box; }.

* {
  box-sizing: border-box;
}
table {
  width: 100%;
  border-collapse: collapse;
}
td {
  border: 1px solid #000;
}
table td:first-child,
table td:first-child input {
  width: 100%;
}
.small {
  width: 20px;
}
.medium {
  width: 40px;
}
<table>
  <tbody>
    <td>
      <div>
        <input type="text" />
      </div>
    </td>
    <td>
      <div>
        <input class="small" type="text" />
      </div>
    </td>
    <td>
      <div>
        <input class="medium" type="text" />
      </div>
    </td>
    <td>
      <div>
        <input class="medium" type="text" />
      </div>
    </td>
  </tbody>
</table>

Comments