0

I need help with the code of a project I've been working on. I can't make my navigation bar fixed so it always appears on the top of the viewport. I understand the rules of CSS position and I've been looking at examples and tutorials, but for some reason, I'm stuck.

I tried to make the position fixed for the navbar and relative to the container, along many other changes. Every thing I tried, it messes up my content. I guess this is one of those moments when you need help.

This is the link to the project and the code of the navbar without any position rules.

https://codepen.io/aitormorgado/pen/MWayXPy

#title-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  font-family: "Aclonica", serif;
  color: #281c1c;
  font-size: 6rem;
  text-transform: uppercase;
  margin: 3rem 1rem;
}

li {
  list-style: none;
}

#header-img {
  width: 6rem;
  padding-right: 1.5rem;
}

#nav-bar ul {
  display: flex;
  flex-direction: column;
  align-items: center;
  font-family: "Libre Baskerville", serif;
  background-color: #990000;
  color: #e0e0e0;
  border-top: 1px solid black;
  border-bottom: 1px solid black;
  text-transform: uppercase;
  font-size: 4rem;
}

#nav-bar ul li {
  border: 2px solid black;
  width: 100%;
  text-align: center;
}

#nav-bar ul li a {
  text-decoration: none;
  color: inherit;
  padding: 1.4rem;
  display: block;
}

#nav-bar ul li:hover {
  background: #cc3300;
}

A million thanks for your help!

  • which part of your HTML you need to fix, As I can see, your hamburger icon is fixed on the left, so you want to fix the red button bar, with there buttons? – Atul Rajput May 01 '20 at 17:33
  • Did you search? https://stackoverflow.com/questions/35048460/how-to-make-a-sticky-navigation-bar might be your answer, check [JSFiddle](http://jsfiddle.net/c0e5ez9m/2) – Ron May 01 '20 at 17:53

1 Answers1

0

as per your question, I just chnaged a small thing in your code and now your header is fixed at the top while scrolling,

all you need to do is use of

#header {
    position: sticky;
    top: 0;
    z-index: 99999;
    background-color: #E0E0E0;
}

on your header. and the background color is given so that rest of the bottom elements will not appear below it while scrolling, If need something else, or I have not understood your question, then feel free to share. just check the codepen here.

inTheFlow
  • 188
  • 2
  • 9
Atul Rajput
  • 4,073
  • 2
  • 12
  • 24
  • One additional note: `position: sticky` is a relatively new CSS feature, so it's a good idea to make sure browser support covers your intended audience: https://caniuse.com/#feat=css-sticky – simmer May 01 '20 at 18:31
  • Agree with simmer... But almost every modern browser supports position sticky. The support rate is almost 93%. Check it here...https://caniuse.com/#feat=css-sticky – Atul Rajput May 01 '20 at 19:34