Shesha
Shesha

Reputation: 2007

Position absolute not working inside position fixed

<div id="main" style="position: fixed">
   <div id="inner" style="position: absolute">
   </div>
</div>

Both main and inner containers taking position: fixed. How to make inner container with position:absolute and main container with position:fixed ?

Upvotes: 8

Views: 13110

Answers (4)

Asim K T
Asim K T

Reputation: 18144

position:absolute will work according to it's parent div's position property. But position:fixed always will take it's position according to the user view port, no matter where the element resides. (No importance to it's parent element)

In the example #main is in fixed position. And have a 200px left property assigned to it. So it will take a 200px left to the viewport, where #inner also have a left:100px, but it will take a 100px left from the parent which is #main. If the inner has also a fixed position, it will take left from the viewport. (Un-comment the commented code in codepen to see it in action)

HTML

<div id="main">
   <div id="inner">
   </div>
</div>

CSS

#main {
  position: fixed;
  background: #cc3;
  width: 500px;
  height: 500px;
  left: 200px;
}
#inner {
  position: absolute;
  width: 100px;
  height: 100px;
  background: #1d3;
  left: 100px;
  top:100px;
}

http://codepen.io/asim-coder/pen/LZNxJM

Upvotes: 3

Mukesh Ram
Mukesh Ram

Reputation: 6328

This may help you:

    #main{ 
  background:#ccc; 
  width:300px;
  height:300px
}  
#inner{
   background:#fff; 
   text-align:center;
   margin:20px; 
   padding:20px
}

<div id="main" style="position: fixed">
   <div id="inner" style="position: absolute">
     inner div
   </div>
</div>

Here is jsfiddle code: https://jsfiddle.net/awvov63a/

Upvotes: 1

b0y
b0y

Reputation: 576

Are you looking for something similar ?

<div id="main">
   <div id="inner">
   </div>
</div>


#main {
  position: fixed;
  width: 100px;
  height: 100px; 
  border: 1px solid #000;

  top: 50px;
  left: 10px;
}

#inner {
  position: absolute;
  width: 10px;
  height: 10px; 
  border: 1px solid #f00;

//  top: 0px;
//  left: 0px;

  top: 10px;
  left: 10px;
}

Upvotes: 3

Mohammad Usman
Mohammad Usman

Reputation: 39332

You need to define top, right, bottom or left properties when using fixed, relative or absolute positioning on an element.

#main {
  background: #000;
  position: fixed;
  height: 300px;
  width: 200px;
  left: 20px;
  top: 10px;
}
#inner {
  background: #f00;
  position: absolute;
  height: 100px;
  width: 100px;
  left: 10px;
  top: 10px;
}
<div id="main">
   <div id="inner">
   </div>
</div>

Upvotes: 3

Related Questions