36

Here is the live demo

I'm trying to put a padded text input inside a td, and I want it to occupy 100% of the width, but it goes outside of the td. I don't understand why that happens, anybody knows?

CSS

  table{
    border: solid 1px gray;
    width: 90%;
  }
  input{ width: 100%; padding:10px; }

HTML

<table>
  <tr>
    <td style="width:150px;">Hello</td>
    <td><input type='text' value='hihihih'/></td>
  </tr>
</table>
ShadowScripter
  • 7,314
  • 4
  • 36
  • 54
Omu
  • 69,856
  • 92
  • 277
  • 407

5 Answers5

65

Explanation

Here's a link to the W3C Box model which explain in detail what happens to your element.

W3C box model - - - - - the two box models

All input elements have borders by default and may also have padding and margins, but most importantly, it follows the W3C box model specifications using the content-box.

This means that if you set the width to 100%, the actual size of the element will be greater than 100% when you include padding/borders, as shown in the images above.


Solution

Add padding to the td to manually adjust the width of the input until it's where you want it to be. Remember that adding padding to the input means you have to add the same amount to the td to counteract the expansion.

Here's a live example

input {
    width: 100%;
    padding: 10px;
    margin: 0px;
}

table .last, td:last-child { 
    padding: 2px 24px 2px 0px; 
}

Alternative solution

You can also do the CSS3 version using box sizing (browser compatability).
This property can be used to switch between the two box models and will make it behave like you'd expect it to.

Here's a live example

input {
    width: 100%;
    padding: 10px;
    margin: 0px;
    box-sizing: border-box;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
}

Here are some possible duplicates of the same question

Community
  • 1
  • 1
ShadowScripter
  • 7,314
  • 4
  • 36
  • 54
5

Simple. 100% width + padding, thats why. You should set padding for wrapper, not input

simoncereska
  • 3,035
  • 17
  • 24
2

you can use box-sizing property for this because padding add width in your input field .

CSS:

input {
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
     box-sizing: border-box;
    padding: 10px;
}

but it's not working IE7

sandeep
  • 91,313
  • 23
  • 137
  • 155
1

Easiest way is to set the padding as a percent of width, subtracted from 100%.

So:

input { 
   width:96%;
   padding:0 2%; 
}
falinsky
  • 7,229
  • 3
  • 32
  • 56
Jim Y
  • 11
  • 1
0

I have found

<td><input type='text' value='hihihih'/>

works funny, try

<td>&nbsp;<input type='text' value='hihihih'/>

it seems to work wonders Though to be truthful was using size= a number as opposed to width=100% for some unknown reason the text was outside the table!