Form Fields and Width: 100%

One thing I ran into when I first started doing responsive design was the misalignment of input and textarea boxes. For example, you’d think the following code would be self-explanatory.

input,
textarea {
     border: 1px solid #ccc;
     -moz-border-radius: 2px;
     border-radius: 2px;
     width: 100%;
}

But it’s not. You end up with a small overlap, exhibited in the image below.

You can see that the textarea is slightly wider than the input[type="text"] box. What causes this? In Chrome, there is 2px of padding on a <textarea> element, and 1px of padding on a <input> element. You could just set your own padding amount and then adjust the width. The problem with that is I don’t want to set the padding to a static amount (say 0.2em) and then have the width be a percentage.

Instead, set the box-sizing property to border-box:

input,
textarea {
     -moz-box-sizing: border-box;
     -webkit-box-sizing: border-box;
     box-sizing: border-box;
     border: 1px solid #ccc;
     -moz-border-radius: 2px;
     border-radius: 2px;
     width: 100%;
}

Now, when the width is set to 100%, the padding is disregarded in the calculation of the width.

Boom! Easy. Support is good too – IE8 and up – as long as you use vendor prefixes. So next time you’re running into width issues on a responsive design, just throw in box-sizing.