Position absolute not working inside position fixed

六月ゝ 毕业季﹏ 提交于 2020-01-04 07:47:50

问题


<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 ?


回答1:


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>



回答2:


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;
}



回答3:


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/




回答4:


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



来源:https://stackoverflow.com/questions/37783835/position-absolute-not-working-inside-position-fixed

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!