Search code examples
htmlcsscss-position

How to make sticky element remain fixed to top of viewport using CSS


I have the following simple navigation menu made up of 2 parts, a skinny banner and a topnav. I have used the sticky property to ensure the topnav is always in view (the skinny banner should not be).

However, how can I ensure the topnav then moves to the top of the viewport when sticky is active (to avoid the gap) - and make another adjustments such as reducing the height of the topnav (when sticky) using CSS?

.skinny-banner {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    background-color: $pastel-green;
    width: 100%;
    height: 40px;
    gap: 24px;
    padding-right: 40px;
    font-size: 14px;
    font-weight: 300;
    background-color: lightyellow;
}

.skinny-nav-menu {
  display: flex;
  gap: 24px;
}

.sticky-container {
    position: fixed;
  width: 100%;
}


/* Add a black background color to the top navigation */
.topnav {
  background-color: #333;
  overflow: hidden;
}

/* Style the links inside the navigation bar */
.topnav a {
  float: left;
  color: #f2f2f2;
  text-align: center;
  padding: 14px 16px;
  text-decoration: none;
  font-size: 17px;
  position: sticky;
}

/* Change the color of links on hover */
.topnav a:hover {
  background-color: #ddd;
  color: black;
}

/* Add a color to the active/current link */
.topnav a.active {
  background-color: #04AA6D;
  color: white;
}

/* Just adding content that can be scrolled to */
.content {
  height: 500px;
  background-color: lightblue;
}
.content-1 {
  height: 500px;
  background-color: lightsalmon;
}
.content-2 {
  height: 500px;
  background-color: lightgreen;
}
<div class="skinny-banner">
  <ul class="skinny-nav-menu">
    <li><a href="#">Item one</a></li>
    <li><a href="#">Item two</a></li>
    <li><a href="#">Item three</a></li>
  </ul>
</div>

<div class="sticky-container">
  <div class="topnav">
    <a class="active" href="#home">Home</a>
    <a href="#news">News</a>
    <a href="#contact">Contact</a>
    <a href="#about">About</a>
  </div>
</div>

<div class="content"></div>
<div class="content-1"></div>
<div class="content-2"></div>


Solution

  • .sticky-container {
      position: -webkit-sticky;
      position: sticky;
      top: 0;
      font-size: 20px;
    }