Sticky navigation bar extending to the right side past margin

43 Views Asked by At

I have a webpage that uses a navigation bar using the following code:

body {
  margin: 3em;
}
#navbar {
  overflow: hidden;
  background-color: #333;
}
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}
<div id="navbar">
  <a class="active" href="javascript:void(0)">Home</a>
  <a href="javascript:void(0)">News</a>
  <a href="javascript:void(0)">Contact</a>
</div>
window.onscroll = function() {myFunction()};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
}

The navbar div extends past the right side of the body even though the body has a margin of 3em. How can I prevent the div from expanding?

I tried adding width: 100%; and box-sizing: border-box; to #navbar css but they make no difference. I cannot think of any more solutions.

1

There are 1 best solutions below

0
Sam Sabin On BEST ANSWER

While the margin does affect the fixed navbar, it is still defining its width as 100% of the html, not 100% of the body.

There's a few ways to fix this. One way is to use the calc() function to subtract the margin(or padding) of the body from the width of the navbar.

Here's a jsfiddle adapting your navbar to use that solution: jsfiddle

I subtract the margin(from both sides, so 6em in your example) from the width of the navbar.

Here is a very similar question(same but they're using padding instead of margin) that may bring more insights: Position fixed with width 100% is ignoring body padding

And here is an article with a similar solution: CSS padding-right disappear when position fixed width 100%