Rad
Rad

Reputation: 1029

position fixed but relative to a container

I have to display two divs (in and out) so that they are positioned one on the left, the other on the right.

Using this css code they fit perfectly great on full screen, but I would like to be able to put them into a parent div, that will be the container

#in{
      position: fixed;
      top: 0;
      left: 0;
      bottom: 0;
      width: 50%;
      overflow: auto;
      font-size: 12px;
      box-shadow: 0 2px 10px rgba(0,0,0,0.2);
    }

#out{
      position: fixed;
      top: 0;
      right: 0;
      left: 50%;
      bottom: 0;
      overflow: auto;
      padding: 10px;
      padding-left: 20px;
      color: #444;
      font-family:Georgia, Palatino, 'Palatino Linotype', Times, 'Times New Roman', serif;
      font-size: 16px;
      line-height: 1.5em
    }

Can anyone help me modify this code for that matter ?

Thank you

Upvotes: 1

Views: 18404

Answers (3)

iConnor
iConnor

Reputation: 20189

When using position: fixed; it fixes the element to the screen. You cannot position it relative to a element with CSS, in fact if you think about what position: fixed does you would never want to position it relative to a element and thought of it sounds impossible to me. A fixed positioned element is is taken out of the flow so that it is relative to the viewport you cannot just put it back in the flow somewhere.

Upvotes: 6

kmm
kmm

Reputation: 618

When using position:fixed; you are positioning the elements relative to the browser window.

To use your own parent container, you'll need to set #in and #out to use position:absolute; and then wrap them in a container, let's say #wrap, that has position:relative; set on it.

Edit: here's a fiddle: http://jsfiddle.net/ktAAa/

Upvotes: 3

Chad
Chad

Reputation: 5408

I'm not sure if this is exactly what you're looking for, but essentially kmmathis is right. http://jsfiddle.net/R8bUQ/

The markup:

<div>
    <div>
    </div>
</div>

and the CSS:

div {
    height: 800px;
    width: 300px;
    background: #f0f;
    margin-top: 80px;
    margin-left: 180px;
    position: relative;
}
div div {
    height: 20px;
    width: 100%;
    background: #0f0;
    position: absolute;
    margin: 0;
    top: 0;
    left: 0;
}

and the JS:

$parent = $('div').eq(0);
$elem = $parent.find('div');

$(window).scroll(function(){ 
    $elem.css('top', $(window).scrollTop());
}).trigger('scroll');

Basically, you set the child to be positioned relative to its parent, and as you scroll, the amount that the window has scrolled sets the top of the element. It's fixed positioning, but is positioned relative to its parent. It's not 100%, but it might give you a basic idea of how to accomplish what you want.

Upvotes: 4

Related Questions