Hat
Hat

Reputation: 1731

text input fill width of container

I have an input inside of a container with varying width that will often change not only between page loads, but also while the user is on the page. I am trying to make it so that the input always fills the container. The method I currently use works perfectly in some browsers, but not all.

html:

<div class="container">
      <input type="text" />
</div>

css:

.container {
    position: relative;
}
input {
    position: absolute;
    left: 0;
    right: 0;
    padding: 2px 4px;
}

The padding makes it such that I can't just set the width to 100%, as this causes the input to overflow by 8px from the padding. On certain browsers (at least Chrome on Windows) the input is not affected by the left and right css tags and just stays the default input width. I know I could do it with js, but I would rather find a simpler solution. Is there any cross-browser way to do this with pure css and no js?

Upvotes: 1

Views: 5499

Answers (3)

TLindig
TLindig

Reputation: 50090

If you use the css property box-sizing: border-box;, the padding will be no problem and you can use width:100%.

See here: CSS Tricks

Here is an example: jsbin

CSS:

.fill {
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;
    width:100%
}

HTML:

<input class="fill" type="text"/>

Upvotes: 8

walmik
walmik

Reputation: 1452

Try using a negative margin of -2px to offset your padding on the left along with box-sizing with browser prefixes... something like this:

http://jsfiddle.net/LKxcv/

CSS:

.container {
    width: inherit;
}
input {
    padding: 2px 4px;
    margin: 0 -2px;
    display:block;
    width: 100%;
    -webkit-box-sizing: border-box;
    -moz-box-sizing: border-box;
    box-sizing: border-box;    
}

Upvotes: 0

Joe Conlin
Joe Conlin

Reputation: 5994

This should work for you:

http://jsfiddle.net/f5g2L/

CSS

.container {
    width: 80%; //change to whatever
}
input {
    display: block;
    padding: 6px 12px;
    width: 100%;
    height: 34px;
    font-size: 1em;
    vertical-align: middle;
}

HTML

<div class="container">
    <input type="text">
</div>

Upvotes: 1

Related Questions