Fixing position relative to parent div

Windbrand picture Windbrand · Mar 2, 2013 · Viewed 36.7k times · Source

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.

Answer

zakangelle picture zakangelle · Mar 2, 2013

Give the parent position: relative, like this:

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

See DEMO.