简体   繁体   中英

I can't make my navigation bar fixed with CSS

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!

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM