sirjay
sirjay

Reputation: 1766

How to fix div to another div with scrollbar

i have

<div id="div1">
  any not fixed text
  but this div has scrollbar

  <div id="div2">
  this div is fixed (without scrollbar)
  </div>

</div>

i need to make div2 fixed to div1, but not fixed to main browser scrollbar. something like "stick div2 to div1".

div1 has scrollbar, that is why i need to fix div2.

if i make this:

#div1 {
    position: absolute;
}
#div1 #div2 {
    position: fixed;
}

it will fix div1 and browser's window both, but i need only div1.

EXAMPLE to test:

<html>
<head>
<style type="text/css">
#div1 {
    border: 1px solid gray;
    position: absolute;
    height: 200px;
    width: 400px;
    overflow-y: scroll;
}
#div1 #div2 {
    position: fixed;
    margin-left: 300px;
}
</style>
</head>
<body>
    <br><br><br>
    <div id="div1">
        <div id="div2">fixed text</div>

            <div style="height: 400px;"></div>
    </div>

    <div style="height: 1400px;"></div>
</body>
</html>

Q1: how to fix div2 to div

Q2: in this case how to float: right div2 to the right side of div1 (on example it is ~ margin-left: 350px;)

thank you.

Upvotes: 3

Views: 3580

Answers (2)

Fergal
Fergal

Reputation: 2474

Fixed is always to the browser window. You can't use it in the context of an element with a scroll bar.

This will work on some levels: http://jsfiddle.net/WP7GB/1/

<div id="div1">
    <div id="div2">fixed text</div>
    <div style="height: 400px;"></div>
</div>
<div style="height: 1400px;"></div>

CSS:

#div1 {
    border: 1px solid gray;
    position: relative;
    height: 200px;
    width: 400px;
    overflow-y: scroll;
}

#div2 {
    position: absolute;
    top:0;
    right:5px;
}

JS:

$(document).ready(function(){

    var $div2 = $("#div2");

    $("#div1").scroll(function(e){

        $div2.css("top", this.scrollTop);

    });        

});

Upvotes: 1

Roimer
Roimer

Reputation: 1459

The problem is that you can't fix div2 to div1, since fixing a div means "to keep the top of the div, measured from the inner top of its nearest positioned container, constant". And by inner top I mean the upper part of the container, which moves up and down as the user scrolls.

The solution (jsfiddle here) would be to fix both div1 and div2 to an outer container. This would be your CSS:

<style type="text/css">
#container{
    border: 1px solid gray;
    position: absolute;
    height: 200px;
    width: 400px;   
}

#div1{
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    overflow-y: scroll; 
}
#div2 {
    position: absolute;
    right: 14px;
    top: 0px;
}​
</style>

And this your HTML

<br><br><br>
<div id="container">
    <div id="div1">
        <div style="height: 800px;"></div>
    </div>
    <div id="div2">fixed text</div>               
</div> 
<div style="height: 1400px;"></div>​​​​​​​​​​​

Upvotes: 1

Related Questions