sanchitkhanna26
sanchitkhanna26

Reputation: 2233

How to let a position-absolute div maintain its postion on document resize

I have a a div with following css

.menu{ 
    width:auto; 
    background-color:#FFF; 
    z-index:14; 
    position:absolute; 
    border:1px solid #d7d7d7; 
    border-bottom:2px solid #ccc;   
    display:none; 
    height:auto; 
    padding-top:2px; 
    padding-bottom:2px;  
}

When you click on the required element, i position this div according the left and top offset of the element clicked.

When the document inreases in height from the top, this div doesn't change its position accordingly. This makes it look very bad.

How do i maintain its position in such cases

Upvotes: 0

Views: 216

Answers (4)

jhunlio
jhunlio

Reputation: 2660

try to wrap your .menu with div wrapper

html

<div class="mainWrap">
  <div class="menu"></div>
</div>

css

.mainWrap {
 position:relative;
}

.menu{ 
    width:auto; 
    background-color:#FFF; 
    z-index:14; 
    position:absolute; 
    border:1px solid #d7d7d7; 
    border-bottom:2px solid #ccc;   
    display:none; 
    height:auto; 
    padding-top:2px; 
    padding-bottom:2px;  
}

Upvotes: 1

Justus Romijn
Justus Romijn

Reputation: 16019

If you position an element using absolute, it will calculate the offset based on the first ancestor with positioning (this means position: absolute; or position: relative).

<body>
  <div id="parent1">
    <div id="child1" style="position: absolute"></div>
  </div>
  <div id="parent2" style="position: relative;">
    <div id="child2" style="position: absolute;"></div>
  </div>
  <div id="parent3" style="position: absolute;">
    <div id="child3" style="position: absolute;"></div>
  </div>
</body>

child1 calculates the offset from the body bacause it's parent doesn't have positioning. child2 and child3 calculate their offset from their parents, because parent2 and parent3 have positioning.

For more information, check the W3C specs about absolutely positioning, relative positioning and floats.

Upvotes: 1

Sancho_UK
Sancho_UK

Reputation: 73

Have you got position: relative; on the parent element?

Upvotes: 0

Ronophobia
Ronophobia

Reputation: 349

Need a fiddle. But I would say use position:relative instead of position:absolute in such cases.

Upvotes: 0

Related Questions