Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fixing position relative to parent div

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.

like image 840
Windbrand Avatar asked Mar 02 '13 00:03

Windbrand


People also ask

Can position fixed be relative to parent?

fixed : the element is removed from the flow of the document like absolutely positioned elements. In fact they behave almost the same, only fixed positioned elements are always relative to the document, not any particular parent, and are unaffected by scrolling.

How do I set parent position relative to div?

The one key thing to remember when trying to position a child div relative to it's parent is that the child should be given the CSS property position:absolute; and the parent set to either position:absolute; or position:relative;.

Can position fixed be relative?

An element with position: fixed; is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled. The top, right, bottom, and left properties are used to position the element. A fixed element does not leave a gap in the page where it would normally have been located.

How do you make a div fixed position?

Set everything up as you would if you want to position: absolute inside a position: relative container, and then create a new fixed position div inside the div with position: absolute , but do not set its top and left properties. It will then be fixed wherever you want it, relative to the container.


1 Answers

Give the parent position: relative, like this:

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

See DEMO.

like image 61
zakangelle Avatar answered Sep 25 '22 13:09

zakangelle