Search code examples
htmlcsslayoutposition

Set div position while page scrolls


I know similar questions have been asked but I've not seen this one. !

I have 3 divs on my page.

WRAP is the main page wrapper and provides a border around the inner divs.

OUTER is the outer div

RIGHT is the div I want to move as the page scrolls.

enter image description here

You can see on this image where RIGHT sits, as the page scrolls down I want right to move with it.

I've tried setting the CSS position to fixed, but if the page is resized this messes up the layout. The css I currently have is :

#wrap 
{ 
    width: 100%; 
    margin: 50px auto; 
    padding: 20px 20px 20px 20px; 
    border:2px solid #800000; 
}

#outer 
{
    margin: auto;
    width: 700px;
    height: 1250px;
    display: table;
    border: 2px solid #000008;
}

#right 
{
    float: right;
    width: 100px;
    height: 100px;
    border: 2px solid #008000;
}

I've created a fiddle with how this currently looks.

How do I get right to move correctly with the page ?

Thanks


Solution

  • RouthMedia's answer works, but if you have different constraints, like "it shouldn't be on top of the content if the window is smaller than the layout"

    To solve that, you can have a window.onresize function that changes the div's right position depending on the constraints you want to have.

    window.onresize = function(event) 
    {
        // is the window smaller than something it shouldn't? calculate the new position
        ("#right").css("right", newpos);
    };
    

    Edit: saw you don't want it out of the outer div.

    One way to do it: When the page loads, set the "right" property to something that puts it inside the outer div. If the screen resizes, update it.

    Another way to do it: use position: absolute, and update the "top" property with the document.scrollTop value when the onscroll event fires.