Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input element with padding and percentage width exceeds parent div

Tags:

html

css

padding

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?

like image 339
ojek Avatar asked May 28 '13 12:05

ojek


3 Answers

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;
}
  • Example Fiddle
  • Browser Compatibility

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.

like image 142
Sirko Avatar answered Sep 22 '22 06:09

Sirko


Why you don't put the padding in percentage too:

input{
   width: 94%;
   padding: 0 3%;
   border:0;
}
like image 28
Joe Avatar answered Sep 20 '22 06:09

Joe


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; }

like image 31
Ashkan Johari Avatar answered Sep 23 '22 06:09

Ashkan Johari