Background issues after adding 'position: fixed'

Hey,

I’m working on a grid project and was having issues with the nav bar on the left side of the page. The background was working fine until I added ‘position: fixed;’ to stop the content from scrolling. but then the background stopped where the content ended, instead of taking up the whole width. I tried 'width: 100%; and the background stretched into the other elements, taking up everything, except the header. I fixed it by changing it to ‘position: sticky’. Just wondering why this was happening and if there’s a better way to do it. Here’s the codepen: https://codepen.io/hey-its-j/pen/xxQWoLv

Thanks

2 Likes

Position sticky is often preferable whenever possible because the element isn’t taken out of the normal document flow. I would use it instead of fixed when possible.


One option is to leave the nav unpositioned and create a wrapper inside it that contains all the elements you want to be fixed.

<nav>
  <div class="fixed-wrapper">
  <img src="" alt="logo">
  <ul>
    <li>Home</li>
    <li>Profile</li>
    <li>Messages</li>
    <li>History</li>
    <li>Tasks</li>
    <li>Communities</li>
  </ul>
  <ul>
    <li>Settings</li>
    <li>Support</li>
    <li>Privacy</li>
  </ul>
  </div>
</nav>
.fixed-wrapper {
  position: fixed;
}

Another thing that might work is to use calc for the width with the code you have now. But it doesn’t seem like a great solution to me.

width: calc(100% / 6);
2 Likes

That’s good to hear that ‘sticky’ is the better way to go. I was thinking it was the other way around. I forgot that fixed is taken out of the normal flow. I guess that’s probably what’s causing the issue.

I tried your code really quick, but couldn’t get it to work. I’m probably doing something wrong. I tried something similar earlier (wrapping the entire nav) without any luck either. Your calc idea works, which is good to know. It sounds like ‘sticky’ is the way to go though, so I’m not gonna worry about getting it to work with ‘fixed’.

Thanks for the help!