14

In my long journey to update my CSS skills from the deprecated dust that they have turned into, I've been playing around with certain CSS properties —particularly z-index —I'm noticing something strange or maybe there's a certain condition.

Example: http://jsfiddle.net/mEpgR/

The element div1's parent is cont, I've made div1's position property set to absolute, yet when I shift it, it's moving relative to its parent. I was under the impression that items set to absolute positioning are outsider regular flow and move only relative to browser port as their parent.

What am I missing?

If the fiddle link does not work, code:

CSS:

.cont {
position:relative; 
height:200px;
top:200px; 
left:100px; 
background: green; width: 200px; 
}

.div1 {
background:red; 
position:absolute; 
top:50px;
}

HTML:

<div class="cont">
<div class="div1">DIV1</div>
</div>
3
  • 4
    This is correct behavior. position:absolute will position an element relative to the closest positioned ancestor. To position it relative to the document, either remove position:relative from the parent, or move the element out of the parent. Jan 17, 2013 at 17:11
  • Read this developer.mozilla.org/en-US/docs/CSS/position
    – j08691
    Jan 17, 2013 at 17:12
  • That's for the quick response; css behavior noted. Jan 17, 2013 at 17:12

1 Answer 1

46

An absolute positioned element is positioned relative to the first parent element that has a position other than static. Since you have it inside a parent with relative it will be absolutely positioned relative to this parent.

You might be looking for fixed position, which is relative to browser window.

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.