Search code examples
htmlcsspositionfixedsticky

How to Make an HTML element to Sticky Position using CSS


I would like to make an HTML element to sticky position using CSS property "position: sticky". But I can't understand why it is not working in my code. I have a double column layout where the second column (sidebar) has 2 elements (news1 & news2). I would like to make "news2" fixed when I scroll. Codesandbox Link: https://codesandbox.io/s/kind-glade-jpkg3v?file=/index.html. I also given the code below. Thanks in Advance!

.container {
  width: 600px;
  display: flex;
  margin: 0 auto;
  gap: 20px;
}

.col1 {
  width: 400px;
}

.col2 {
  width: 200px;
}

.article {
  height: 500px;
  background: #efefef;
  padding: 20px;
  margin-bottom: 20px;
}

.news1 {
  background: #efefef;
  padding: 20px;
  margin-bottom: 20px;
  height: 200px;
}

.news2 {
  position: sticky;
  position: -webkit-sticky;
  top: 0;
  height: 200px;
  padding: 20px;
  background: #efefef;
}
<div class="container">
  <div class="col1">
    <div class="article">
      <h2>Article One</h2>
    </div>

    <div class="article">
      <h2>Article Two</h2>
    </div>

    <div class="article">
      <h2>Article Three</h2>
    </div>
  </div>

  <div class="col2">
    <div class="sidebar">
      <div class="news1">
        <h3>News One</h3>
      </div>

      <div class="news2">
        <h3>News Two</h3>
      </div>
    </div>
  </div>
</div>


Solution

  • Your .sidebar is limited by the height of its two children .news1 and .news2. Its height needs to be the same as its parent .col2's height:

    .sidebar {
        height: 100%;
    }
    

    Try it:

    .sidebar {
      height: 100%;
    }
    
    .container {
      width: 600px;
      display: flex;
      margin: 0 auto;
      gap: 20px;
    }
    
    .col1 {
      width: 400px;
    }
    
    .col2 {
      width: 200px;
    }
    
    .article {
      height: 500px;
      background: #efefef;
      padding: 20px;
      margin-bottom: 20px;
    }
    
    .news1 {
      background: #efefef;
      padding: 20px;
      margin-bottom: 20px;
      height: 200px;
    }
    
    .news2 {
      position: sticky;
      position: -webkit-sticky;
      top: 0;
      height: 200px;
      padding: 20px;
      background: #efefef;
    }
    <div class="container">
      <div class="col1">
        <div class="article">
          <h2>Article One</h2>
        </div>
    
        <div class="article">
          <h2>Article Two</h2>
        </div>
    
        <div class="article">
          <h2>Article Three</h2>
        </div>
      </div>
    
      <div class="col2">
        <div class="sidebar">
          <div class="news1">
            <h3>News One</h3>
          </div>
    
          <div class="news2">
            <h3>News Two</h3>
          </div>
        </div>
      </div>
    </div>