Search code examples
htmlcssflexboxsticky

HTML/CSS - My div is just not being sticky and I do not know why


For some reason I cannot understand why this is not working. My only difficulty: The header div is just not being a sticky.

HTML:

<div class="header">
    <div class="header-content">
        <img src="mycoollogo.svg" class="logo" />
    </div>
</div>


CSS:
.logo {
  height: 3rem;
}

.header {
  position: -webkit-sticky; /* Safari Support */
  position: sticky;

  height: 3.5rem;
  margin-top: 0rem;
  margin-left: 0rem;
  margin-right: 0rem;

  background: var(--accent-color);

  color: white;
}

.header-content {
  height: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;

  margin-left: 6rem;
  margin-right: 6rem;
}

Solution

  • your code looks fine the only issue I see is that you should be using top:0 along with the position sticky to make this work.

    Here I have modified your code a bit to make it visible use the run snippet tab below and try to scroll, your header should be sticky now.

    .logo {
      height: 3rem;
    }
    
    .wrapper {
      position: relative;
    }
    
    .header {
      position: -webkit-sticky; /* Safari Support */
      position: sticky;
      top: 0;
      height: 3.5rem;
      margin-top: 0rem;
      margin-left: 0rem;
      margin-right: 0rem;
    
      background: var(--accent-color);
    
      color: white;
    }
    
    .header-content {
      height: 100%;
      display: flex;
      flex-direction: row;
      align-items: center;
    
      margin-left: 6rem;
      margin-right: 6rem;
    }
    
    .top-content {
      background: blue;
      height: 100px;
      position: sticky;
    }
    
    .bottom-content {
      background: red;
      height: 5000px;
    }
    <div class="wrapper">
      <div class="top-content"></div>
      <div class="header">
        <div class="header-content">
            <img src="mycoollogo.svg" class="logo" />
        </div>
    </div>
    <div class="bottom-content"></div>
    </div>