How to make an element with fixed position relative to its parent, not the whole screen?

First Understand Positioning:

Fixed Positioning OR [ position:fixed ]

An element with fixed position is positioned relative to the browser window.

Relative Positioning OR [ position:relative ]

A relative positioned element is positioned relative to its normal position.

Absolute Positioning OR [ position:absolute ]

An absolute position element is positioned relative to the first parent element that has a position other than static.

So in your case your parent div should have position:relative and your child div should have position:absolute instead of position:fixed

Reference Link


From reading your question I assume you have something like this:

 <div class="sidebar">
    <div class="fixed" style="position: fixed;"></div>
 </div>

Unfortunately as you probably know by now, top, left, right or bottom will always act relative to the browser window on positon: fixed elements.

The solution is wrapping your .fixed div with another div, and do all the positioning you have to do on that same wrapper and not on the .fixed div. Let me demonstrate:

The HTML:

<div class="sidebar">

    <div class="helper">
        <div class="fixed"></div>
    </div>

 </div>

The CSS:

​.sidebar {
    position: relative;
}

.helper {
    position: absolute;
    top: XYZ; left: ZYX; /*where XYZ and ZYX would
                           be the values you were 
                           trying before to give to .fixed*/
}

.fixed {
    position: fixed;
}

See it in action in this fiddle: http://jsfiddle.net/joplomacedo/T2PL5/

Tags:

Css