Reputation: 5
In this page, why is only the top margin and left margin is visible? What happens to the right margin and bottom margin?
html,
body {
display: block;
height: 100%;
}
main {
box-sizing: border-box;
height: 100%;
width: 100%;
background-color: rgb(0, 0, 0);
margin: 24px;
}
<!-- body element added automatically -->
<main>Wtf</main>
And if I make some changes which fixes the margins:
html,
body {
display: flex;
height: 100%;
width: 100%;
}
main {
height: 100%;
width: 100%;
background-color: rgb(0, 0, 0);
margin: 24px;
}
<!-- body element added automatically -->
<main>Wtf</main>
Where did the bottom margin go? Why is it not visible?
Upvotes: 0
Views: 88
Reputation: 1597
These could be of help:
My experience taught me:
position/transform
+ top/left/right/bottom
OR flex/align-items
flex/align-items
position/transform
and top/left/right/bottom
Upvotes: 0
Reputation: 36426
A couple of things - browser's can put default margins on eg. body (in this case 8px when I look) so having a body with width 100% (the viewport) causes overflow because with that margin things are now too big. Then secondly, the child element gets a 24px margin and that is shown top and left but on the right and bottom there is no room for it.
If we don't constrain the body size to 100% (100vw) but make main into 100vw width and 100vh height see what happens:
html,
body {
display: flex;
rheight: 100%;
rwidth: 100%;
}
main {
height: 100vh;
width: 100vw;
background-color: rgb(0, 0, 0);
margin: 24px;
}
<!-- body element added automatically -->
<main>Wtf</main>
When you scroll you can see that the whole main is there plus its margins.
If you want everything to fit within the viewport but main to have margins of 24px still then its width and height can be calculated e.g. calc(100% - (2 * 24px))
html,
body {
display: flex;
height: 100%;
width: 100%;
}
main {
height: calc(100% - (2 * 24px));
width: calc(100% - (2 * 24px));
background-color: rgb(0, 0, 0);
margin: 24px;
}
<!-- body element added automatically -->
<main>Wtf</main>
Upvotes: 0
Reputation: 2850
You're using box-sizing: border-box;
, which makes it so the padding
and border
are considered included within the width
& height
properties.
This is a good choice in general, but it is important to realize that unlike padding
and border
, it does not affect margin
.
-
Because of this, since your inner element has a width of 100% plus a 24px margin, it will always be too big and cause a scrollbar to appear.
Upvotes: 1