How can I have a textbox that inherits the width of it's container?
For example I have a div that has a textbox inside it.
<div id='content' style='width:100%;'>
<input type='text' name='txtUsername'>
</div>
What I wanted to do is when I resize my browser, the text box must follow the width of it's parent div.
With the code above, the textbox always overflow it's container whenever I resize the browser to a smaller width.
To create the inputs of the same width, we have to use some CSS attributes in our program. box-sizing: It defines how the height and width of the element are calculated. moz-box-sizing: It is supported in the Mozilla Firefox browser only. -webkit-box-sizing: It is supported in the Google Chrome browser only.
With JavaScript, you can use the setAttribute() method to set the value of the size attribute on the input text box. You can also dynamically change the width of a text box to match the length of the input. We can easily do this by setting the size attribute on key events.
The width attribute specifies the width of the <input> element. Note: The width attribute is used only with <input type="image"> . Tip: Always specify both the height and width attributes for images. If height and width are set, the space required for the image is reserved when the page is loaded.
Method 2: We can make the display attribute of the child container to table-row and display attribute of parent container to table, that will take all the height available from the parent div element. To cover all the width, we can make the width of parent div to 100%.
You should use box-sizing:border-box
together with width:100%
.
This way input
will fit 100% of container's width but will not overflow it because of added input
's padding:
#content input
{
width:100%;
box-sizing:border-box;
-moz-box-sizing:border-box;
}
Live demo: http://jsfiddle.net/745Mt/1/
More information about box-sizing
CSS property with examples: http://css-tricks.com/box-sizing/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With