Padding within inputs breaks width 100%

Sandman picture Sandman · Sep 4, 2009 · Viewed 79.4k times · Source

Ok, so we know that setting padding to an object causes its width to change even if it is set explicitly. While one can argue the logic behind this, it causes some problems with some elements.

For most cases, you just add a child element and add padding to that one instead of the one set to 100%, but for form inputs, that's not a possible step.

Take a look at this: http://sandman.net/test/formcss.html

The second input has its padding set to 5px which I very much prefer to the default setting. But unfortunately that makes the input grow 10px in all directions, including adding 10px to the 100% width.

Problem here is that I can't add a child element inside the input so I can't fix it. So the question is:

Is there any way to add padding inside the input while still keeping the width 100%? It need to be 100% since the forms will render in different width parents so I don't know beforehand the width of the parent.

Answer

Víctor Dieppa Garriga picture Víctor Dieppa Garriga · Dec 17, 2012

Using CSS3 you can use the property box-sizing to alter how the browser calculate the width of the input.

  input.input {
    width: 100%;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
  }

You can read more about it here: http://css-tricks.com/box-sizing/