George Yu
George Yu

Reputation: 23

Flexbox affected by margin afterwards

I am trying to create a simple web page with a navigation bar and a title centered in the page. However, the margin of the title div somehow affected the positioning of the navigation bar.

I think this is caused by the margin collapsing of two adjacent block-level boxes? I have tried to fix this problem by adding a <br> after the navigation bar, it worked, but I think it is not elegant.

Is there a better method to achieve what I want?

Below is my simplified HTML code:

<header id='navbar-bg'>
  <div id='navbar'>
    <ul>
      <li>Foo</li>
      <li>Bar</li>
    </ul>
  </div>
</header>

<div id='body'>
  <h1 id='search-title'>This is a title</h1>
</div>

And the CSS style:

#navbar-bg {
    position: fixed;
    width: 100%;
}

#navbar {
    display: flex;
    align-items: center;
}

#body {
    margin-top: 200px;
}

Since the position of #navbar-bg is fixed, I want the navigation bar as a whole to be fixed, and the margin-top of #body should not affect the navigation bar. Yet the margin-top moved both the #body and the navigation bar down, which is strange.

I want to fix this problem using an elegant solution, not adding a <br> after header.

Upvotes: 2

Views: 42

Answers (2)

David Deprost
David Deprost

Reputation: 5110

For a navbar it's probably best to be on the left of the body, so you could do this in your CSS:

#navbar-bg {
  position: fixed;
  width: 20%;
  float: left;
}

#navbar {
  display: flex;
  align-items: center;
}

#body {
  margin-top: 200px;
  float: right;
  width: 80%;
}

Upvotes: 0

Mohammadreza Ghorbani
Mohammadreza Ghorbani

Reputation: 188

You have to set a top: 0px to the #navbar-bg element. According to Mozilla:

The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the viewport, except when one of its ancestors has a transform, perspective, or filter property set to something other than none (see the CSS Transforms Spec), in which case that ancestor behaves as the containing block. (Note that there are browser inconsistencies with perspective and filter contributing to containing block formation.) Its final position is determined by the values of top, right, bottom, and left.

So, when you don't use top for the #navbar-bg element, it will fall back to it's initial values, which is relative to body. So the body margin is also present in that element.

Upvotes: 2

Related Questions