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?
border-box tells the browser to account for any border and padding in the values you specify for an element's width and height. If you set an element's width to 100 pixels, that 100 pixels will include any border or padding you added, and the content box will shrink to absorb that extra width.
What is meant by width 100%? if you specify width:100%, the element's total width will be 100% of its containing block plus any horizontal margin, padding and border.
The box-sizing property allows us to include the padding and border in an element's total width and height. If you set box-sizing: border-box; on an element, padding and border are included in the width and height: Both divs are the same size now!
Description. This property sets the maximum content width of a block or a replaced element. This maximum width does not include padding, borders, or margins.
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
Try setting the padding to 5% and width to 90% (100-5x2)
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