问题
I have a table that has fixed width, and inside the table I need to have some inputs(text)
that has the same width of the table, but I don't want the text of the inputs to be at left:0
, I want them to have some padding from the left. But when I put the padding to those inputs the width changes to more than 100%
.
Here the HTML:
<table cellspacing="25">
<tr>
<td><input type="text" placeholder="lalala"></td>
</tr>
</table>
And this is the CSS.
table {
background-color: red;
width: 300px;
}
table input {
width: 100%;
padding-left: 10px;
}
How can I ensure that the width of the input element is 100%
the width of the table cell?
Check the fiddle
回答1:
add this css rule to your input:
box-sizing: border-box;
The box-sizing property is used to tell the browser what the sizing properties (width and height) should include.
Should they include the border-box? Or just the content-box.
Here is a snippet:
table {
background-color: red;
width: 300px;
}
table input {
width: 100%;
padding-left: 10px;
box-sizing: border-box;
}
<table cellspacing="25">
<tr>
<td><input type="text" placeholder="lalala"></td>
</tr>
</table>
回答2:
You can use box-sizing: border-box; (support) in which "The width and height properties include the padding and border, but not the margin." in your CSS for the specified elements as @1l13v has done in his answer:
table input {
box-sizing: border-box;
}
Or you can use the calc function (support):
table input {
width: calc( 100% - 10px );
}
回答3:
Another option would be to calculate the width and padding of the input with percentages. If the sum of the content, border, margin, and padding of the element is 100%
then it should fit how you would like. See the box-model
concept in css: http://www.w3schools.com/css/css_boxmodel.asp
All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.
The box model allows us to add a border around elements, and to define space between elements.
For example, if you want 10% padding
on the left then the width should be 90%
.
See this fiddle: http://jsfiddle.net/3nk07y1x/1/
CSS:
table {
background-color: red;
width: 300px;
}
table input {
width: 90%;
padding-left: 10%;
}
回答4:
The width of the table will be the width plus the padding. Try subtracting some percentage points from the width like this:
table input {
width: 90%;
padding-left: 1em;
}
I would also change pixels to ems, because these are a little bit more stable on different screen resolutions.
来源:https://stackoverflow.com/questions/32854597/padding-changes-width-inside-table