Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bootstrap, keep div fixed after scrolling to it

I am using Bootstrap, and have a simple page here

If you click the green "Go" button and scroll down the page, more records are loaded. I wanted the advert in the right hand column to e.g. "stick" to 10 px from the top of the page once I have scroll down the page and reached the advert div.

As you can see, instead it remains half way down the page.

I have this as the HTML for the div:

<div class="col-md-3">     <div data-spy="affix">         <script type="text/javascript">         .. advert         <a href="#" class="back-to-top">Back to Top</a>     </div> </div> 

I wondered if there is a way to get it to do what I'm trying to do, as I'm a bit stuck?

Thanks

like image 580
4532066 Avatar asked Feb 05 '15 09:02

4532066


People also ask

How do I make a Div always stay on top?

The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.


1 Answers

Bootstrap 4.0+ update

Please note that the affix is removed from bootstrap as mentioned here. As of 2018, I also suggest you to avoid jQuery and move to angular, react or vue for better coding practices.

To make that happen now from bootstrap 4.0, you need to use the sticky-top class.

Sample code:

<div class="card sticky-top"> ...Something </div> 

And it looks like this:

enter image description here

If you want some padding & margin, you can set that up or add another div with the same class on top of it, etc. Be creative :)

like image 116
Fangming Avatar answered Sep 19 '22 14:09

Fangming