Creating a dynamic height sticky sidebar and footer in Bootstrap 5 using CSS/HTML

Looking to implement a sticky sidebar feature with a header and footer that remain visible while the middle content scrolls. The overall height of the page will vary, so I plan to use Bootstrap 5 grid for structuring.

<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57515c5d565025535340550055404d">[email protected]</a>/dist/css/bootstrap.min.css">
<style>
  body {
    background-color: #f1f1f1;
    margin: 15px 0;
  }
  header {
    margin-bottom: 15px;
  }
  .block {
    background-color: #fff;
    border: 1px solid #ccc;
    padding: 15px;
  }
  .sidebar .block {
    width: 100%;
    max-height: 100vh;
    height: calc(100vh - 295px);
    min-height: calc(100vh - 295px);
    overflow-y: auto;
  }
  .sticky {
    position: sticky;
    top: 15px;
  }
  .header,
  .footer {
    height: 50px;
    text-align: center;
    color: #fff;
    background-color: #000;
  }
</style>
</head>

<body>
<div class="container-fluid">
<header>
  <div class="block">
    hi, my height can change.
  </div><!--/.block -->
</header>
<div class="row">
  <div class="col-sm-9">
    <div class="block">
      dd<br />dd<br />...all your content here...
    </div><!--/.block -->
  </div><!--/.col -->
  <div class="col-sm-3">

    <div class="sticky sidebar">
      <div class="header">HEADER</div>
      <div class="block">
        ...content of the sidebar...
      </div><!--/.block -->
      <div class="footer">FOOTER</div>
    </div><!--/.wrapper -->
  </div><!--/.col -->
</div><!--/.row -->
</div><!--/.container-fluid -->
</body>
</html>

Check out this link on JSFiddle for reference.

To see how it looks in action, take a look at these previews: Preview when at the top of the page | Preview when at the bottom of the page

Answer №1

To achieve this functionality, you can utilize jQuery in your code.

Take a look at the code snippet provided below for guidance:

$.fn.isInViewport = function() {
  var elementTop = $(this).offset().top;
  var elementBottom = elementTop + $(this).outerHeight();

  var viewportTop = $(window).scrollTop();
  var viewportBottom = viewportTop + $(window).height();

  return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(document).ready(function() {
  $(window).on('resize scroll', function() {
    if ($('header').isInViewport()) {
      $('.sidebar .block').css('height', 'calc(100vh - 180px)');
    } else {
      $('.sidebar .block').css('height', 'calc(100vh - 130px)');
    }
  });
});
body {
  background-color: #f1f1f1;
  margin: 15px 0;
}

header {
  margin-bottom: 15px;
}

.block {
  background-color: #fff;
  border: 1px solid #ccc;
  padding: 15px;
}

.sidebar .block {
  width: 100%;
  max-height: 100vh;
  height: calc(100vh - 180px);
  min-height: calc(100vh - 195px);
  overflow-y: auto;
  transition: all 0.2s ease-in-out;
}

.sticky {
  position: sticky;
  top: 15px;
}

.header,
.footer {
  height: 50px;
  text-align: center;
  color: #fff;
  background-color: #000;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/bootstrap/dist/css/bootstrap.min.css">
  <script src="https://cdn.jsdelivr.net/npm/bootstrap/dist/js/bootstrap.bundle.min.js" integrity="sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js" integrity="sha512-aVKKRRi/Q/YV+4mjoKBsE4x3H+BkegoM/em46NNlCqNTmUYADjBbeNefNxYV7giUp0VxICtqdrbqU7iVaeZNXA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
</head>

<body>
  <div class="container-fluid">
    <header>
      <div class="block">
        Hi there! My height is dynamic.
      </div>
    </header>
    <div class="row">
     <!-- Code continues with layout and content -->
    </div>
  </div>
</body>

</html>

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

Containers do not line up properly with each other. Adjusting the width leads to unexpected consequences

As someone who is new to HTML and CSS, I am facing a challenge with aligning the items within a navigation bar on my website. The list serves as a navigation bar and is contained inside the "inner header" div. While I was able to align the entire "nav" con ...

Tips for extracting content data from a Microdata meta tag within a designated class

I am attempting to extract all the values associated with dateCreated. My current approach involves using Selenium webdriver with Python. <div class="bv-content-datetime" role="presentation"> <meta itemprop="dateCreated" content="2018-08-28" ...

IE causing Ul LI Menu to not display as Block

I'm encountering an issue with my menu. It displays correctly in Firefox and Chrome, but in IE8 it appears as a vertical list instead of a horizontal menu. I have included a doctype and I am linking to the HTML5 JavaScript via Google, so I'm not ...

Top method for independently scrolling overlapping elements in both the x and y directions

Sorry if this is repeating information. I have a structure of nested divs like this: -container -row In order to enable scrolling without the default scrollbar appearing, each container and row has an additional container. My goal is to be able to scrol ...

Utilize AngularJS to Access Global JavaScript Variables

I recently encountered a situation where I needed to incorporate some dynamic functionality into a website I was building. This led me to AngularJS, which I decided to integrate into certain parts of the site rather than the entire thing. Within my JavaSc ...

Are there any tools you rely on for speeding up the process of developing html/css?

Have you heard of zen-coding? It's a script that generates markup based on a css-esque selector like this: div#foo > p*6 This code would generate: <div id="foo"> <p></p> <p></p> <p></p> & ...

I am attempting to assign a default value to a TextField by retrieving data from a GetMapping call in React, however, the value is not being successfully set

I am facing an issue with setting a default value for a TextField in my code. Even though I am trying to populate it with data from a GetMapping call, the value is not being set as expected. Here is the JSON response I receive from the API call: { "id": 1 ...

Internet Explorer and CSS: How to eliminate a highlight that pops up when the button is clicked

Could you please check out this website in Internet Explorer (I've tried it on the latest version as well as older versions.) On the above link, there are two circular buttons at the bottom of the page. In IE, when you click on a button, a semi-trans ...

The submission button in Bootstrap 3 becomes disabled upon clicking, preventing the data from being successfully transferred to the database

Currently, I am in the process of developing a signup page using bootstrap. To validate my form, I have integrated the plugin. Despite all validations being successful, an issue arises when I attempt to submit the form - the submit button is disabled and ...

Guide on automatically removing a DOM element in Jquery after a set amount of time

Is there a way to delete an HTML element after a specific period of time? If a certain condition is met before the allotted time, I want to pause the timer from deleting the element. Here's a snippet of code for reference: <ul> <li dat ...

Text reveal animation in Framer Motion is not functioning as expected

I'm having trouble locating the issue in my code, and the text reveal feature isn't working. Interestingly, a simple animation works fine, indicating that there's no problem with the import or library: import { motion } from ...

Troubleshooting React child problems in TypeScript

I am facing a coding issue and have provided all the necessary code for reference. Despite trying numerous solutions, I am still unable to resolve it. export class JobBuilderOptimise extends React.Component<JobBuilderOptimiseProps & JobBuilderOptim ...

Is there a peculiar issue with CSS float:right in IE9?

These are the styles I'm using: For the parent container: div.musicContainer { width:820px; height:54px; margin-bottom:20px; } And for the child containers: div.hardcorePlayer { width:400px; float:left; border:n ...

What is the best way to eliminate the space between two paragraphs?

Check out my awesome image! I need some help with formatting HTML data into text. Can anyone advise me on how to eliminate the space between two paragraphs? func processGetDescriptionResponse(json: JSON) { let status = json.dictionaryObject!["statu ...

The HTML attribute "hasbox" specifies the presence of a box within the element

I am currently working on resolving some rendering issues specifically in IE9 and have encountered a tag attribute that I am not familiar with - hasbox. Upon further investigation, it seems like IE is injecting this attribute at runtime as it does not app ...

Guidelines on retrieving an HTML element from a source document

To change a specific HTML section identified by a tag id in source code consisting of both HTML and PHP, I need to use PHP. If the code is purely HTML, a DOM parser can be utilized; otherwise, if there are multiple nested DIVs, regex with preg_match might ...

Automatically scroll to the end of the data retrieved through ajax

I am currently developing a live chat website for my users and I am using ajax to fetch the chat messages. However, I am facing an issue where whenever I enter a new message, it does get added to the database and displayed, but the scroll doesn't auto ...

Utilizing jQuery to toggle a dropdown box based on multiple checkbox selections

After conducting a search, I came across a helpful resource on Stack Overflow titled Enable/Disable a dropdownbox in jquery which guided me in the right direction. Being new to jQuery, I found it useful to adapt code snippets to suit my needs. Now, my que ...

Combining D3.js tooltip positioning with CSS overflow styling

I am encountering an issue with displaying tooltips in D3 when combined with CSS overflow. Is there a solution available for this particular problem? CSS code: #chart1 { overflow-x: auto; overflow-y: hidden; max-width: 800px; max-height: 22 ...

SVGs are not resizing correctly in Internet Explorer and there is unnecessary blank space around them

Recently, I made the decision to switch to using SVG symbols for one of my projects. However, I encountered a challenge as I needed these SVGs to be responsive. My main objective was to minimize the number of HTTP requests, leading me to explore the option ...