Scrollable content with sticky positioning using CSS3 and JavaScript

I successfully implemented a sidebar using the position: sticky property and it is functioning perfectly.

To identify colors in the following text, refer to the script below.

When scrolling, the black area remains fixed while the green area sticks to its position relative to the red top bar. However, the content within the green area exceeds the viewport's height.

Once the scroll nears the bottom of the page and the overflown green area matches the remaining scroll height, the green area begins to move.

I am looking to have the green area scroll along with the black area and stay fixed when it reaches the end. Essentially, I want it to behave like Facebook's sidebar or similar to this example:

Is achieving this behavior possible with position:sticky, possibly by integrating some JavaScript and jQuery?

I prefer not to resort to the old method of using position:fixed like certain other libraries do when we have the convenience of position:sticky.

* {
  font-family: "Courier New", Courier, monospace;
  color: #fff;
  text-align: center;
}

.container {
  height: 2000px;
  position: relative;
}

.topbar {
  height: 50px;
  line-height: 50px;
  background: #D16666;
  position: -webkit-sticky;
  position: sticky;
  border-radius: 5px;
  top: 0px;
  z-index: 10;
}

.sidebar {
  position: -webkit-sticky;
  position: sticky;
  border-radius: 5px;
  top: 60px;
  height: 1000px;
  line-height: 1000px;
  background: #B6C649;
  border-radius: 5px;
  position: -webkit-sticky;
  position: sticky;
}

.row {
  margin-left: 0;
  margin-right: 0;
  position: relative;
}


.main-content {
  height: 1800px;
  line-height: 1800px;
  background: #2C4251;
  border-radius: 5px;
  top: 10px;
}

.col-8 {
  top: 10px;
  padding: 0;
  padding-left: 0 !important;
}
<html>

<head>
  <link href="https://static.aftertutor.com/css/bootstrap.min.css" rel="stylesheet" />
</head>

<body>
  <div class="container">
    <div class="topbar">Topbar</div>
    <div class="row">
      <div class="col-4">
        <div class="sidebar">Sidebar</div>
      </div>
      <div class="col-8">
        <div class="main-content">Main Content</div>
      </div>
    </div>
  </div>
</body>

</html>

Answer №1

To achieve a fixed position for the sidebar with a specific amount of space above it, you can use the following JavaScript function:

Simply add this function to your code:

function setSidebarPosition() {
    var sidebar = document.getElementById("sidebar");
    var sidebarHeight = sidebar.clientHeight;
    var availableHeight = window.innerHeight;
    var sidebarTop =  availableHeight - sidebarHeight - 20;
    // Adjust the value of 20px based on your requirements
    sidebar.style.top = sidebarTop + "px";
}
* {
  font-family: "Courier New", Courier, monospace;
  color: #fff;
  text-align: center;
}

.container {
  height: 2000px;
  position: relative;
}

.topbar {
  height: 50px;
  line-height: 50px;
  background: #D16666;
  position: sticky;
  top: 0px;
  z-index: 10;
}

.sidebar {
  position: sticky;
  top: 60px;
  height: 1000px;
  line-height: 1000px;
  background: #B6C649;
  margin-top: 10px;
}

.main-content {
  height: 1800px;
  line-height: 1800px;
  background: #2C4251;
  top: 10px;
}

.col-8 {
  padding: 0;
  padding-left: 0 !important;
}

button {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 30px;
    background-color:blue;
    z-index: 10;
}
<head>
  <link href="https://static.aftertutor.com/css/bootstrap.min.css" rel="stylesheet" />
</head>

  <div class="container">
    <div class="topbar">Topbar</div>
    <div class="row">
      <div class="col-4">
        <div class="sidebar" id="sidebar">Sidebar</div>
      </div>
      <div class="col-8">
        <div class="main-content">Main Content</div>
      </div>
    </div>
  </div>
  <button onclick="setSidebarPosition();">Click me</button>

Answer №2

The functionality works as intended. Imagine a box with a height of 1800px containing a sticky element with a height of 1000px. The sticky element remains in place until it reaches the bottom of its relative parent, at which point it becomes relatively positioned. This creates the effect of a fixed element.

UPDATE: Erroneous code snippet and unhelpful comments have been removed

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Stretch element to reach the edge of the container

I need help with positioning an input and a textarea inside a container that has a height of 52.5vh. I want the textarea to start right below the input and expand all the way to the end of the container. How can I achieve this layout? Both elements should ...

Error Encountered: Angular JS Throwing Unhandled Injection Error

I am having trouble validating the fields in my index.html and js files. I keep seeing errors, even after trying different versions of angular-route.min.js and angular.js. AngularJs | Basic Login Form <body ng-app="myApp"> ...

Guide on how to navigate users to a new page using react-router-dom v6 within a class-based component

I am facing an issue where I need to redirect the user to '/dashboard' after logging in, but I do not want to use history.push() from react-router-dom v5.2.0 as I have react-router-dom v6 installed. Is there another alternative to achieve this re ...

Issue with DIV height in Internet Explorer occurs only when application is accessed using server name

Encountering a unique issue specific to IE (confirmed in v8 and v9). When utilizing jquery to determine the height of a div: $('#sys_MainPage').height() In Chrome, Firefox, and when accessing using the IP address, this code returns around 26 ...

The console.log for a GET request in Express Router is displaying undefined parameters

After searching extensively on SO for a question similar to mine, I have come to the realization that my issue should be quite straightforward. The closest thread I discovered was this link. My current focus is on learning Node.JS, and I am in the process ...

Retrieve all attributes of an element with the help of jQuery

I am attempting to extract all the attributes of an element and display their names and values. For instance, an img tag may have multiple unknown attributes that I need to access. My initial idea is as follows: $(this).attr().each(function(index, element ...

Is it possible to use the .map() method on an array with only 3 items and add 2 additional placeholders?

I need to iterate through an array of 5 items in a specific way: list.slice(0, 5).map((i) => { return <div>{i}</div> }); However, if the array only contains 3 items, I would like to add placeholders for the remaining 2 items in my reac ...

Designing personalized sass components

Seeking advice on developing a custom CSS unit that can be utilized in Sass with Node.js. Is there a tutorial available for creating a Sass plugin specifically for this purpose? For instance, I am looking to establish a unit called "dpx" which functions as ...

Error encountered while trying to retrieve Instagram JSON data via request due to an abrupt end of input

I am attempting to retrieve the JSON data from Instagram's URL: . When I enter this URL in my browser, it displays the JSON information. However, I want to be able to access this data using Express so that I can extract any necessary information. co ...

Having difficulty in replicating and obtaining flash video content from a website through HTML coding

I'm having trouble downloading a flash video, as traditional download software isn't working. I attempted to directly access the video from the html script itself, following this tutorial : https://www.youtube.com/watch?v=waE3J0Jej_0 The script ...

Exploring Grails Assets, Redirections, Secure Sockets Layer, and Chrome

Using Grails 2.1.1 with the resources plugin, I have encountered an issue when incorporating the jstree library which comes with themes configuration: "themes":{ "theme":"default", "dots":false, "icons":true } The JavaScript in the library locat ...

The use of backdrop-filter results in artifacts appearing in rounded corners

I am experiencing an issue with a CSS animation where I have an element that fades and child elements with a backdrop-filter to blur the background in Safari. There are two specific problems: The element's rounded borders are showing dark shadow ...

Issues arise with the loading of models while attempting to utilize Mocha testing

I'm currently in the process of using mocha for testing my express application. In terms of folder structure, it looks like this: myapp |-app |--models |-test |--mocha-blanket.js |--mocha |--karma |-server.js The server.js file serves as my express ...

Difficulty with button click functionality in Selenium IDE

Hi there, I am trying to use the clickAndWait xpath=//button[contains(.,'Next')] command in Selenium IDE, but despite showing up in the test, it is not clicking on the button labeled 'Next'. The button I am referring to has an id of pmc ...

Issue with inline Javascript not functioning correctly when partial is rerendered in Ruby on Rails version 3.1

I am facing an issue in my project where inline JavaScript in a partial, using some instance variables, does not run when the partial is rerendered after a successful ajax call. Could someone please provide guidance on how to solve this problem? For exam ...

Issues with AJAX formData functionality

I'm having difficulties with the formData in my Ajax calls. I have searched extensively for solutions and tried various approaches, including using getElementById, but nothing seems to work. The form in question has an id of add-lang-form: <form ...

Executing an http.get request in Angular2 without using RxJS

Is there a method to retrieve data in Angular 2 without using Observable and Response dependencies within the service? I believe it's unnecessary for just one straightforward request. ...

Navigating through various locators with Protractor to fill an array

Currently utilizing protractor, my aim is to iterate through a collection of locators (each with unique identifiers) in order to retrieve the displayed text and then compare it against an array of expected values. I have encountered examples similar to th ...

Troubleshooting: AngularJS not displaying $scope variables

I have a question that has already been answered, but the suggested solutions did not work for me. Everything seems to be fine, but the content within curly brackets is not displaying on screen. <div ng-controller="Hello"> <p>The I ...

Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js. In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this ...