Input Width Equal To Parent Element
Problem
Making a text input equal the width of the parent element is a pain in the ass. I know because I’ve been trying to find the right solution for some time now. Specifically using jQuery Mobile, but I think I got it! If you’re a pixel-perfect designer like me, you want all your form elements to have equal widths. I want mine to span the full width of the content container. First I started using percentages, but noticed that the widths were not consistent between text inputs and other form elements. Also with percentages, they look okay at a certain window width, but different when the window width changes. Then I tried media queries with percentages to handle the window width issue, but that’s just too much if you just want inputs consistently the width of the content container. This is important because you don’t know what size screen or device the user will be looking at your application in.
Solution
The CSS3 box-sizing property seems to be working great for me. If you’re worried about older browsers that don’t support CSS3, then don’t use this method.
Here’s the HTML:
<div id="container" > <label for="username">Username:</label> <input type="text" name="username" value="" /> </div>
Here’s the CSS:
#container input { width:100%; } input, select, textarea { box-sizing: border-box; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; }
According to w3schools, this is why the border-box value works: The specified width and height (and min/max properties) on this element determine the border box of the element. That is, any padding or border specified on the element is laid out and drawn inside this specified width and height. The content width and height are calculated by subtracting the border and padding widths of the respective sides from the specified ‘width’ and ‘height’ properties.