I have a box #box
with width: 100%, height: 100%, padding: 5px, margin: 5px; border: 5px;
I need in HTML5 layout correctly display that.
Now i have that:
But i need fit block in body area.
Code:
<!DOCTYPE html>
<style>
body,html {
width: 100%;
height: 100%;
margin: 0;
}
#box {
width: 100%;
height: 100%;
border: 5px solid red;
padding: 15px;
margin: 20px;
}
</style>
<body>
<div id="box">
Text will be here
</div>
</body>
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.
Yes, as per the CSS 2.1 Specification, all non-negative values are valid for width, that includes percentage values above 100%.
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!
width: 100%; will make the element as wide as the parent container. Extra spacing will be added to the element's size without regards to the parent.
The browser does excacly what you are telling him to do :) However I think you don't like the overflow it has.
What happens is that your #box
expands because of your border and padding. You can make these properties inset, so it does not expand your element. You can do this with box-sizing
:
#box {
width: 100%;
height: 100%;
border: 5px solid red;
padding: 15px;
/*margin: 20px;*/
box-sizing: border-box;
}
However you can not do the same with the margin
, because the element is pushing itself from the body: it does what it supposes to do.
You can make a workaround by doing the same thing as above:
body
{
padding: 20px;
box-sizing: border-box;
}
You will use the padding on the body instead of the margin on the #box
.
Update
To prevent the double padding space, you should only apply it on the body element (or html, but i prefer the body as that is your visual element in the end).
According to w3c specs for Box Model
The rendered width of a box type element is equal to the sum of its width, left/right border and left/right padding.
So that means the values of padding
and border-width
affects the total width of the element. So here you are adding the 15px
of the padding along with 5px
of borders with 100% of actual width of the element.
So overall it exceed the widow size that's why it comes with horizontal scroll.
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