clarkk
clarkk

Reputation: 27685

element with width 100% and padding

how can you make an element with width 100% and padding fit inside another element without changing the width of the parent?

var inp = $('<input type="text" style="padding:4px; width:100%" />')
      .appendTo('<div style="width:200px"></div>');

Upvotes: 0

Views: 411

Answers (2)

DanielB
DanielB

Reputation: 20230

You can't use width: 100% and padding: 4px together in this case. The element will always be 8px wider than its parent. You have to go with pixel values for your input element. In your case it would be width: 192px.

The box model always (except some older IE versions) adds the padding (and border) to the elements width. So if the width is 100% each pixel of horizontal padding will make the element wider than its parent.

You could fake your input style this way by achieving the 100% width with padding.

<div style="width:200px">
    <div style="border: 1px solid blue; background: #fff">
        <div style="padding:2px 4px">
            <input type="text" style="display:block; width:100%; border:0; padding:0" />
        </div>
    </div>
</div>

Upvotes: 0

Luca Matteis
Luca Matteis

Reputation: 29267

input elements are display: inline by default. Make them display: block if you want the width: 100% to work.

Upvotes: 1

Related Questions