问题
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