Ad

Bootstrap 4 Sticky-top Stops Working

- 1 answer

I'm using sticky-top feature on Bootstrap's cards, as user scrolls they would follow. But I've found a weird behaviour, in which cards in one column would become 'unsticky' as user would go past the last card in that column.

As I was writing an example fiddle for this question I found it worked as intended:

as you scroll here, a card in middle column keeps following

So I took an example straight from my project and cleaned it up:

here the card in middle column stops following as soon as it goes past last card

I don't think it's a bug, but I'm not sure what is breaking the sticky-top feature. How can I prevent that from happening?

Ad

Answer

By default, Bootstrap columns are set to 100% of the height of their parent element. By wrapping the cards in the second column in an additional div element, you changed the parent container that the ".sticky-top" class is referencing from the Bootstrap column to the ".tags" div. If you want to keep the ".tags" div, create a rule in your CSS file so that it will match the height of its parent column:

.tags {
  height: 100%;
}

Or just use the Bootstrap ".h-100" class in your opening ".tags" div to accomplish the same thing:

<div class="tags h-100">

Edit: As "ajax333221" demonstrated (jsfiddle.net/8pLfg5n1), the two preceding solutions cause the ".tags" div to overflow its parent container. This happens because the top card in the second column is outside the ".tags" div. Thus, the parent column height assigned to ".tags" begins where the first card ends rather than at the top of the column.

Since a jQuery library is already necessary for many Bootstrap 4 features, it can be utilized here to calculate and assign a custom height to the ".tags" div to fit the remaining space in the parent container:

$(document).ready(function(){
    var colHeight;
    //Get column height
    $('.tags').each(function(){ 
      colHeight = $(this).parent().height();
    });
    //Subtract height of cards preceding .tags div
    $('.topCard').each(function(){
      colHeight -= $(this).height();
    });
    /*Set .tags div height to remaining space in 
    column to prevent overflow*/
    $('.tags').each(function(){
      $(this).css('height', colHeight);
    });
 }); 

This script utilizes a ".topCard" class that I added to the visible cards in the same column above ".tags" in order to differentiate them.

<div class="card bg-primary w-100 topCard">

Here is the updated version of the demo provided by "ajax333221": https://jsfiddle.net/8pLfg5n1/33/

Ad
source: stackoverflow.com
Ad