Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

I run into situation that when user scroll down, a part of the sidebar gets fixed position, however when I catch the position and apply fixed css to the sidebar element, it gets fixed to whole screen, not just the parent (which is sidebar)

how do I setup this correctly?

like image 896
Ahmed Fouad Avatar asked Jul 11 '12 11:07

Ahmed Fouad


2 Answers

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

like image 196
Ahsan Khurshid Avatar answered Nov 11 '22 14:11

Ahsan Khurshid


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/

like image 23
João Paulo Macedo Avatar answered Nov 11 '22 13:11

João Paulo Macedo