How to make an element width: 100% minus padding?

275,154

Solution 1

box-sizing: border-box is a quick, easy way to fix it:

This will work in all modern browsers, and IE8+.

Here's a demo: http://jsfiddle.net/thirtydot/QkmSk/301/

.content {
    width: 100%;
    box-sizing: border-box;
}

The browser prefixed versions (-webkit-box-sizing, etc.) are not needed in modern browsers.

Solution 2

This is why we have box-sizing in CSS.

I’ve edited your example, and now it works in Safari, Chrome, Firefox, and Opera. Check it out: http://jsfiddle.net/mathias/Bupr3/ All I added was this:

input {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

Unfortunately older browsers such as IE7 do not support this. If you’re looking for a solution that works in old IEs, check out the other answers.

Solution 3

Use padding in percentages too and remove from the width:

padding: 5%;
width: 90%;

Solution 4

You can do it without using box-sizing and not clear solutions like width~=99%.

Demo on jsFiddle:
enter image description here

  • Keep input's padding and border
  • Add to input negative horizontal margin = border-width + horizontal padding
  • Add to input's wrapper horizontal padding equal to margin from previous step

HTML markup:

<div class="input_wrap">
    <input type="text" />
</div>

CSS:

div {
    padding: 6px 10px; /* equal to negative input's margin for mimic normal `div` box-sizing */
}

input {
    width: 100%; /* force to expand to container's width */ 
    padding: 5px 10px;
    border: none;
    margin: 0 -10px; /* negative margin = border-width + horizontal padding */ 
}

Solution 5

Use css calc()

Super simple and awesome.

input {
    width: -moz-calc(100% - 15px);
    width: -webkit-calc(100% - 15px);
    width: calc(100% - 15px);
}​

As seen here: Div width 100% minus fixed amount of pixels
By webvitaly (https://stackoverflow.com/users/713523/webvitaly)
Original source: http://web-profile.com.ua/css/dev/css-width-100prc-minus-100px/

Just copied this over here, because I almost missed it in the other thread.

Share:
275,154
Hailwood
Author by

Hailwood

I could tell you all about me... but I'd prefer to let my work do the talking for me!

Updated on April 08, 2021

Comments

  • Hailwood
    Hailwood about 3 years

    I have an html input.

    The input has padding: 5px 10px; I want it to be 100% of the parent div's width(which is fluid).

    However using width: 100%; causes the input to be 100% + 20px how can I get around this?

    Example