skip to Main Content

I have a container div which has a border. I’m trying to make the top border sticky on content scroll but it’s not working.

.container{
  border: 10px solid red;
  position: sticky;
}
.content{
    height: 500px;
  overflow: scroll;
}
<div class="container">
    <div class="content">
    
  </div>
</div>

When I scroll the top border doesn’t stick.

3

Answers


  1. I feel like you might be looking for this result, am not sure though.

    I’ve placed overflow: scroll in .container instead and included height property for this element.

    <html>
    <head>
    <style>
    .container{
      border: 10px solid red;
      position: sticky;
      height: 300px;
      overflow: scroll;
    }
    .content{
        height: 500px;
        border: 1px solid black;
    }
    </style>
    </head>
    <body>
    
    <h2>Overflow: hidden</h2>
    
    <div class="container">
        <div class="content">
        
      </div>
    </div>
    
    </body>
    </html>
    Login or Signup to reply.
  2. I made some minor edits to your code, and now everything works correctly:

    1. For sticky positioning to work, you must specify at least one of the top, right, bottom, or left properties.

    2. The overflow property defines how content behaves when it exceeds the element’s padding—whether it extends horizontally, vertically, or both.

    here is the code:

     .container {
         border: 10px solid red;
         position: sticky;
         top: 0;
     }
     .content {
         height: 40px;
         overflow: scroll;
         background: yellow;
      }
    

    Please add some paragraphs within the .content class to observe the scrolling effect.

    Login or Signup to reply.
  3. The .container element needs to have the position: sticky and the top property set to determine when it should become sticky. Also, the position: sticky element should not be the scrollable container itself, but rather a child element inside it.

    .container {
      border: 10px solid red;
    }
    
    .sticky-header {
      position: sticky;
      top: 0;
      background-color: white; 
      z-index: 1;
    }
    
    .content {
      height: 500px;
      overflow: scroll;
    }
    
    <div class="container">
        <div class="sticky-header">
            <!-- Your sticky top content goes here -->
            Sticky Header
        </div>
        <div class="content">
            <!-- Your scrollable content goes here -->
            Content goes here...
        </div>
    </div>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search