I have this:
<div class="wrapper">
<input type="text"/>
</div>
div{
border: 1px solid red;
width: 300px;
}
input{
width: 100%;
padding: 10px;
}
I need the input to be 100% of the parent div, but also I need this input to have 10px padding. Results can be seen here: http://jsfiddle.net/pdJYF/
How can I achieve this?
Add box-sizing
to your input field:
input{
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
width: 100%;
padding: 10px;
}
The underlying "problem" is the box model of HTML/CSS. As you can see in the illustration of the respective MDN article each element's box has 4 different areas: margin box, border box, padding box and content box.
When you assign measures (width
or height
) to the element, this is applied to one of these areas. If the area is, e.g., the content box, then for the total size of the element margin, border and padding is added. So you wont set the total dimensions of the box, but one of its contained boxes.
The CSS property box-sizing
tells the browser, which box to use, when calculating the element's dimensions. The default value is content-box
. So in the above example values for margin, border and padding get added and hence the element is too big. By setting the box model to border-box
, only the margin gets added to the dimensions (which is zero here) and the elements fits.
Why you don't put the padding in percentage too:
input{
width: 94%;
padding: 0 3%;
border:0;
}
You must decrease 2x padding from left and right, and decrease 2x for any pixel you want use like this and insert your input's width.
For example: 20px (paddings left & right) + 2px (borders left & Right )= 22px
300px - 22px = 278px
div { border: 1px solid red; width:300px; }
input { width: 278px;padding: 10px; }
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