Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why are the margins not working properly?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading