0

I'm trying to layout a somewhat simple page with a navigation drawer and an app bar. The nav drawer should be the full height of the page, the app bar should be at the top of the page and the full width of the area that is not covered by the nav drawer. The page content should then be to the right of the nav drawer and beneath the app bar.

<div class="nav-drawer"></div>
<div class="nav-drawer-adjust">
  <div class="app-bar"></div>
  <div class="app-bar-adjust">Page content here</div>
</div>

The .nav-drawer-adjust has a left margin to push the rest of the page to the right of the nav drawer. The .app-bar-adjust has a top margin to push the page content beneath the app bar.

.nav-drawer {
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  width: 256px;
}

.nav-drawer-adjust {
  width: calc(100% - 256px);
  position: relative;
  height: 100%;
  margin-left: 256px;
}

.app-bar {
  position: absolute;
  top: 0;
  width: 100%;
  height: 64px;
}

.app-bar-adjust {
  margin-top: 64px;
  height: calc(100% - 64px);
}

However, with that HTML and that CSS, I get this result:

body is not at the top of the page

The margin-top on the .app-bar-adjust seems to "set" where the top of the body element is. And because the body is no longer at the top of the page, the .app-bar isn't either. But why?? Can someone please explain what is happening?

Here is a Code Pen of the situation.


I can "fix" this problem in one of two ways:

  1. By adding a wrapper element with display: flex. That makes sense, but I don't understand why it is necessary
  2. By changing the margin-top on .app-bar-adjust to be a padding-top instead. But this is undesirable for other layout reasons.

But these two solutions are both workarounds and I don't think address the actual problem here.

Zach Olivare
  • 3,805
  • 3
  • 32
  • 45
  • Would changing the positioning of the `app-bar` div to `fixed` be the solution to your problem? See Codepen example: https://codepen.io/mikehermary/pen/qBEVKXx?editors=1100 – Mike Hermary Jan 03 '20 at 21:18
  • (1) flex can fix this because there is no margin-collapsing in flexbox context (2) padding doesn't collapse with margin – Temani Afif Jan 03 '20 at 21:23

0 Answers0