Fixing position relative to parent div

39,360

Solution 1

Give the parent position: relative, like this:

.parent {
    position: relative;
}
.child {
    position: absolute;
    top: 0;
}

See DEMO.

Solution 2

I've created this CodePen for you.

From your description, it is half way there.

but they'll move when I scroll the entire browser window.

You will need to use iframe or some kind of JavaScript solution.

Share:
39,360
Windbrand
Author by

Windbrand

Updated on March 02, 2020

Comments

  • Windbrand
    Windbrand over 4 years

    Is it possible to fix an element's position relative to the parent div, not the browser window?

    Say I have:

    <div id="pagecontainer">
    
        <div id="linkspage">
    
            <div class="sidelinks">
                <a href="#page1" class="link">Link 1</a>
                <p>
                <a href="#page2" class="link">Link 2</a>
                <p>
                <a href="#page3" class="link">Link 3</a>
                <p>
                <a href="#page4" class="link">Link 4</a>
                <p>
            </div>
    
            <div class="linkscontent">
                content of links page
            </div>
    
        </div>
    
        //OTHER PAGES
    
    </div>
    

    Basically a page with two sections, the left section is a list of links, while the right section is the page's content. I want the content to be scrollable, but the links to remain fixed to the parent #pagecontainer so they don't scroll when #pagecontainer scrolls, but they'll move when I scroll the entire browser window.

    I've already tried the JQuery "fixto" plugin: https://github.com/bbarakaci/fixto. But I can't use that one because my pages fade in/out and the script bugs out when the parent element (#pagecontainer) has an alpha of 0, it thinks the parent element is gone and has nowhere to fix to.

    Thanks.

  • Windbrand
    Windbrand over 11 years
    It doesn't work. I've tried to set both #pagecontainer and #linkspage to relative, only #pagecontainer to relative, and only #linkspage to relative, with .sidelinks as absolute, nothing works.