0

I'm trying to make inner div fixed relative to it's parrent div. I made an example of my code on jsfiddle. Problem is when you scroll div. It is no longer on it's position. My html looks like:

 <div class="outer">
   <div class="inner1">
     Lorem ipsum dolor
   </div>
   <div class="inner2">

   </div>

</div>

and css

    .outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}

.inner1{
  position: absolute;
  width:50px;
  height: auto;
  border: 1px solid blue;
  top: 10px;
  right: 10px;
}
.inner2{
  width: 500px;
  height: 500px;
}

Is there any way to make inner1 fixed relative to outer only using css ?

tprieboj
  • 1,680
  • 6
  • 31
  • 54
  • _"The CSS specification requires that `position:fixed` be anchored to the `viewport`, not the containing positioned element."_ Refer [this](http://stackoverflow.com/a/7823145/1746830) answer.. – Rayon May 07 '16 at 09:51
  • fixed isn't relative to parent! It always stays at the given position! – Stack learner May 07 '16 at 10:15
  • I know that it is not ! I just want inner1 stay on its position even when u scroll ... I know that one of the solutions is calculate offset in JS and use position: fixed.. But my question is, if u can do it using only css – tprieboj May 07 '16 at 10:23

4 Answers4

1

try this...

 <style>
.outer{
  position: relative;
  width: 400px;
  height: 300px;
  border: 1px solid black;
  overflow: auto;
}

.inner1{
  position: fixed;
  width:50px;
  height: auto;
  border: 1px solid blue;

}
.inner2{
  width: 500px;
  height: 500px;
}
</style>
0

You can try this:

.inner1 {
        position: fixed;
        width: 50px;
        height: auto;
        border: 1px solid blue;
        top: 10px;
        right: calc(100% - 400px); // 400px is the outer div's width
    }
Pranab Mitra
  • 401
  • 1
  • 4
  • 9
0

Here is working JSfiddle

<div class="container">
<div class="header">title</div>
<div class="cont_elements">
    <div class="element">......</div>
    <div class="element">......</div>
    <div class="element">......</div>
</div>

and css will be

.header {
    position: absolute;
    top:0;
    /* scrolling out of view :-( */
    z-index:2;
    background-color:pink;
}
.container {
    position:relative;
    width:200px;
    height:400px;
    background:gold;
}
.cont_elements {overflow-y:scroll; height:100%;}
.element {
    position: relative;
}
Kristián Stroka
  • 698
  • 1
  • 8
  • 23
0

Just change .inner1

.inner1{
    position: fixed;
    width:50px;
    height: auto;
    border: 1px solid blue;
    margin-top: 10px;
    left: 330px;
}
Sadegh
  • 107
  • 1
  • 4