Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Contain input text to 100% width

Tags:

So when I set the input like this example the text box, because it has a border and padding by default, will be wider than 200px.

<div style="width:200px; background-color:red;">     <input type="text" name="fname" style="width:100%;"/> </div> 

I know I can force the text box to fit within the 200px by setting a class to the input tag and tagging it with this CSS

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

Is there a better way to get this text box to size correctly, i.e. to fill 100% as I want it to do? I cannot use fixed sizes. I am using CSS themes so the text box padding, margins, etc are not known at compile time. They can be changed out by the user on the fly. So the solution must work regardless of what the text box's padding, border, and margin is.

like image 579
w.donahue Avatar asked Jan 21 '12 08:01

w.donahue


People also ask

How do I make input width fit content?

Use the span. text to fit width of text, and let the input have same size with it by position: absolute to the container.

How to set the width of a text field in html?

The size attribute specifies the visible width, in characters, of an <input> element. Note: The size attribute works with the following input types: text, search, tel, url, email, and password. Tip: To specify the maximum number of characters allowed in the <input> element, use the maxlength attribute.

What is the width in html?

Definition and UsageThe width attribute specifies the width of the element, in pixels.


1 Answers

I think you have already answered your own question. box-sizing: border-box; is really the only CSS means of getting the element to fit inside its parent. css-tricks goes into great detail about this here.

http://css-tricks.com/box-sizing/

I am unaware of any other CSS you could use other than using javascript to perform some calculations and then modifying your input elements.

like image 173
mrtsherman Avatar answered Sep 21 '22 12:09

mrtsherman