Table cells overflow despite box-sizing: border-box

此生再无相见时 提交于 2021-01-29 09:11:18

问题


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.


回答1:


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




回答2:


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>


来源:https://stackoverflow.com/questions/54280521/table-cells-overflow-despite-box-sizing-border-box

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!