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?
>Solution :
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>