htmlcsshtml-tableborder-boxbox-sizing

Table cells overflow despite box-sizing: border-box


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.


Solution

  • 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