0

I want to add padding to the cells of my table, but this causes text, inputs, etc inside the table to overflow. From other Stack Overflow discussions, I've gathered that the answer is to set box-sizing: border-box, but this isn't working for me.

Below is a minimal example to illustrate the problem.

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

table,
th,
td {
  border: 1px solid black;
  padding: 1.5%;
}

table {
  border-collapse: collapse;
}
<table>
  <tr>
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit</td>
    <td><input value=1></td>
  </tr>
</table>

With padding of 1.5%, the input box sticks out of the right end of its cell. If padding is changed to 0, then the input box fits snugly. I want to keep the padding but make the input box fit.

2 Answers2

3

set the width of the input so it will fill the table cell

input{
    max-width: 100%;
}

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

table,
th,
td {
  border: 1px solid black;
  padding: 1.5%;
}

table {
  border-collapse: collapse;
}
input {
  max-width: 100%;
}
<!DOCTYPE html>
<table>
  <tr>
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit</td>
    <td><input value=1></td>
  </tr>
</table>

EDIT: thanks @javier Rey for the correction

Daniel Vafidis
  • 357
  • 1
  • 10
  • That works perfectly. :) What about when ordinary text overflows a table cell? For example, this happens when one column has a lot of text in it, causing it to be wide, and a different column with much less text (which is therefore narrow) has a long word that can't be broken apart. Setting `td { width: 100%; }` leads to odd behavior where the first column takes up most of the width of the whole table... – Brian Tomasik Jan 20 '19 at 20:56
  • 1
    you could use a fixed width and add an overflow on the cells that have more text maybe ? – Daniel Vafidis Jan 20 '19 at 21:05
  • With the above style rule, the width of all input elements (not just the `text` type) is forced to be `100%` in all cases, no matter the container element. Setting the `max-width` rather than the `width` would be more appropriate (see answer below). – Javier Rey Jan 21 '19 at 23:31
1

Ensure the input inside the td only spans to the cell's width.

* {
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
}

table {
  border-collapse: collapse;
}

th, td {
  border: 1px solid black;
  padding: 1.5%;
}

td>input {
  max-width: 100%;
}
<table>
  <tr>
    <td>Lorem ipsum dolor sit amet, consectetur adipiscing elit</td>
    <td><input value="1"/></td>
  </tr>
</table>
Javier Rey
  • 1,539
  • 17
  • 27