Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a div follow as you scroll?

Tags:

html

scroll

I have a div on the left hand side which includes the business hours and weather. I would like that div to scroll down and up according to how the user scrolls. So it would follow and move up and down with the page. How would I attempt this? This is my website judystropicalgarden.com

Thanks

like image 819
user1165861 Avatar asked Jul 09 '12 16:07

user1165861


People also ask

How do you make a div stick when scrolling?

To make an element sticky, do: make_sticky('#sticky-elem-id'); When the element becomes sticky, the code manages the position of the remaining content to keep it from jumping into the gap left by the sticky element. It also returns the sticky element to its original non-sticky position when scrolling back above it.

How do I make a div stick to another div?

You can use the CSS position property in combination with the z-index property to overlay an individual div over another div element. The z-index property determines the stacking order for positioned elements (i.e. elements whose position value is one of absolute , fixed , or relative ).


3 Answers

You can either use the css property Fixed, or if you need something more fine-tuned then you need to use javascript and track the scrollTop property which defines where the user agent's scrollbar location is (0 being at the top ... and x being at the bottom)

.Fixed
{
    position: fixed;
    top: 20px;
}

or with jQuery:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').css('top', $(this).scrollTop());
});
like image 81
Matthew Cox Avatar answered Oct 20 '22 12:10

Matthew Cox


The post is old but I found a perfect CSS for the purpose and I want to share it.

A sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport - then it "sticks" in place (like position:fixed).

    div.sticky {
        position: -webkit-sticky; /* Safari */
        position: sticky;
        top: 0;
        background-color: green;
        border: 2px solid #4CAF50;
    }

Source: https://www.w3schools.com/css/css_positioning.asp

like image 38
BugliL Avatar answered Oct 20 '22 14:10

BugliL


Using styling from CSS, you can define how something is positioned. If you define the element as fixed, it will always remain in the same position on the screen at all times.

div
{
    position:fixed;
    top:20px;
}
like image 17
Arcym Avatar answered Oct 20 '22 14:10

Arcym