Input elements that fill their container

Previously, this post advocated the use of “text-indent” on a padding-less, border-less, 100% width input. This works, but it’s quite clunky, and old versions of IE don’t support text-indent, so it just looks bad. A much better solution is to

Just use box-sizing.

As pointed out in the comments, the simplest solution is to simply change the box-sizing model of the input element to “border-box”, rather than the default “content-box”. In the example below, I’ve given the containing div a 4px whiteborder.

<div style="background:#000; width:200px; border: solid 4px #fff;"><input  style="-moz-box-sizing: border-box; box-sizing: border-box; display: block; padding: 4px; width: 100%; height: 100%; background: #fff; opacity: 0.5; border: solid 1px #666;" type="text" value="text input"/></div>

Note that for Firefox, you still need to use the -moz- prefix; it’s supported unprefixed in all the other major browsers, though.

Updated 2012-08-03.

3 thoughts on “Input elements that fill their container”

  1. another solution set

    -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box;

    to the input

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.