Greg Gum Greg Gum - 22 days ago 10
CSS Question

Why does padding-left in a textbox cause width to be greater than 100%

I have a div with 1 em of padding.

Inside is a textbox, with the width set to 100%. This looks fine and as expected, with the width set 1 em inside the div.

However, when I add 1 em of padding-left to the textbox, the text box width is widened by 1 em, ignoring the padding on the right. So it now touches the edge of the div.

How do I resolve this?

<div style="padding:1em;background-color:pink">
<input style="width:100%;padding-left:1em" />
</div>

Answer

Because padding is added on top of the original width. Unless you set box-sizing: border-box which will allow the total width be calculated with padding and border included.

#outer {
  background: red;
  padding: 1em;
}
#text {
  width: 100%;
  padding: 1em;
  box-sizing: border-box;
}
<div id="outer">
  <input type="text" id="text">
</div>