Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Position Absolute With Respect to a Parent Element Acting as Relative

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>
like image 629
brooklynsweb Avatar asked Jan 17 '13 17:01

brooklynsweb


People also ask

How do you absolute position relative to parents?

Absolute In position: relative , the element is positioned relative to itself. However, an absolutely positioned element is relative to its parent. An element with position: absolute is removed from the normal document flow. It is positioned automatically to the starting point (top-left corner) of its parent element.

How do I fix position relative to parent?

To position an element "fixed" relative to a parent element, you want position:absolute on the child element, and any position mode other than the default or static on your parent element. This will position childDiv element 50 pixels left and 20 pixels down relative to parentDiv's position.

Can an element be position absolute and relative?

Clearly, nothing can be absolute and relative at the same time. Either you want the element to position itself based on another ancestor's position or based on the page flow.

Is position absolute or relative?

position: relative places an element relative to its current position without changing the layout around it, whereas position: absolute places an element relative to its parent's position and changing the layout around it.


1 Answers

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.

like image 168
Mike Brant Avatar answered Sep 24 '22 19:09

Mike Brant