Reputation: 10753
Basically I have a div that I want at 100% width. However, I also want it to have some padding. But when I add the padding, the width is added to it, meaning that my div now goes off-screen and there's a horizontal scroll bar.
Usually I compensate by just making the div a lower percentage (like 95%, or 90%).
I was wondering if there are any more elegant ways to handle this situation?
Upvotes: 7
Views: 3817
Reputation: 3969
There are four major things involve in CSS Box Model. i) Margin ii) Border iii) Padding iv) Content
When we set width then we are essentially setting width of CONTENT so adding padding means overall increase of width.
Please go through following resources and you'll get to know everything.
http://www.w3.org/TR/CSS2/box.html
http://css-tricks.com/the-css-box-model/
And you can handle this situation using % or even if you calculate px width correctly if you have also set border or even want to set margins.
element{
width: 96%;
padding: 0 2%;
}
Upvotes: 0
Reputation: 943563
By default a div is width: auto
which (assuming normal positioning, display and lack of floating) will cause it to fill its container (accounting for margins, padding and border).
Just leave it at width: auto
instead of setting an explicit or percentage width.
Upvotes: 0
Reputation: 74046
Have a look at box-sizing.
.example {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
Per default the width of an element is computed with regard to its content box. So an applied padding is added to the width. If you change the box model to border-box
, the padding is included in the width. For compatibility have a look at caniuse.com
Upvotes: 11