25

I have had this issue for years and I've seen similar questions before, but none of them have addressed the fact that when setting width: 100% on an element - paddings, margins and borders will increase the width.


Have a look at this Fiddle.

The white topmost text box is a standard text box with it's width set to 100%. As you can see it overflows it's parent because of the margin, padding and border settings.

The green text box is styled like a div using position: absolute. This works like a dream in webkit browsers but nowhere else.

The red div is the control - I want the input to act just like that.


Are there any hacks/tricks I can employ to have my text inputs act just like the red div in all modern browsers, in other words, fit inside the padding of the parent? Please edit my Fiddle or create your own to accompany your answer. Thanks!

Hubro
  • 56,214
  • 69
  • 228
  • 381

3 Answers3

40

You can:

input#classic
{
    width: 100%;
    padding: 5px;
    margin: 0;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -o-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;        
}

JS Fiddle demo.

Note I removed the margin, since that was causing an overflow, and set the box-sizing to determine the width of the element including the width of the borders and padding.

Nikola K.
  • 7,093
  • 13
  • 31
  • 39
David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • 1
    When I fake the margin using the parent's padding property this is actually a [completely viable solution](http://jsfiddle.net/mowglisanu/qfUre/29/). +1 Thanks for the answer – Hubro Jul 30 '12 at 22:35
  • this answer should have more thumbs up! Thanks!! – jbartolome Aug 09 '16 at 18:54
2

Using calc to compensate for the margin and box-sizing for the padding

input#classic
{
    padding: 5px;
    margin: 5px;
    width: -webkit-calc(100% - 10px);
    width: -moz-calc(100% - 10px);
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    -o-box-sizing: border-box;
    -ms-box-sizing: border-box;
    box-sizing: border-box;
}

FIDDLE

Musa
  • 96,336
  • 17
  • 118
  • 137
  • 2
    This seems like the ***correct*** solution, but unfortunately [browser support is still lacking](http://caniuse.com/calc). Also your example doesn't work in FireFox for some reason. – Hubro Jul 30 '12 at 22:33
  • Too bad it's not supported in Opera though – Hubro Jul 30 '12 at 22:49
0

Try with display:table-cell property

  display:table;
  display:table-cell;

may it help you

please check this link

Style input element to fill remaining width of its container

Community
  • 1
  • 1
Prashobh
  • 9,216
  • 15
  • 61
  • 91