Home > Mobile >  Why are the margins not working properly?
Why are the margins not working properly?

Time:01-06

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?

CodePudding user response:

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.

CodePudding user response:

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>

CodePudding user response:

These could be of help:

  1. Collapsing Margins
  2. Break Margins

My experience taught me:

  1. for spacing around a single element => use paddings.
  2. for spacing between multiple elements => use margins.
  3. for centering horizontally => use margins.
  4. for centering vertically => position/transform top/left/right/bottom OR flex/align-items
  5. for organising multiple elements with common alignments => flex/align-items
  6. For self alignments => use position/transform and top/left/right/bottom
  • Related