16

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
  • 555
  • 4
  • 13
  • 21

2 Answers2

43

Give the parent position: relative, like this:

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

See DEMO.

zxqx
  • 5,115
  • 2
  • 20
  • 28
  • 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. – Windbrand Mar 02 '13 at 02:47
1

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.

Alen
  • 121
  • 6