Css - parent position is absolute and child position is relative and vice versa

I have a div that hosts another div. Ok I get the case where parent position:relative

and child position:absolute

. I don't understand what happens when

  • parent position is absolute and child position is relative
  • the parental position is absolute and the child's position is absolute.
  • parent position is relative and child position is relative

I am using the JSbin example from Why is the wrapping of an element's absolute position based on its parent right associated? but the question relates to the concept of positioning in general

+3


source to share


2 answers


Learn more about absolute, relative, and fixed position and how they differ here , but I'll try to answer your question about relationships specifically.

position: absolute

will place this element in the closest parent with position

other thanstatic

. Static is the default for everyone.

position: relative

a bit strange, because it really affects this element and not its own position. He simply tells her children: "Put yourself in relation to me if you have position: absolute

." A position

of fixed

or absolute

does the same thing (which means its positioned children will position themselves relative to their borders), but these styles also affect their own position on the page. Element c position: relative

won't look different, but it can be children.

So, consider this situation:

<div class="parent">
     <div class="child">
           <div class="grandchild"></div>
     </div>
</div>

      



If it grandchild

does position: absolute

, it will position itself relative to the browser window, because there is no s parent position

other than the default static

.

If it parent

also has position

of relative

, absolute

or fixed

, grandchild

will be located relative to the borders parent

.

However, if it child

also has position

of relative

, absolute

or fixed

, grandchild

will position itself relative to the bounds child

, since it is the closest parent with a position

except static

.

Thus, it relative

affects the child elements and absolute

also fixed

affects the element itself as well as its children.

And remember that position: fixed

bypasses all parents relative

and absolute

and always positions itself relative to the browser window.

+8


source


1 - if the mother is relative and the child is absolute: the mother listens to her child. as if protecting him. kinda .. 2 - if they are both absolute: they have nothing to do with each other. they are strangers to each other. 3 - if the parent is an absolute and relative child: they are related. the child moves (width and height) to the side or away from his mother.



It will always be a little weird, there is a lot of great writing about it, but for me it is always just toggling between absolute and relative until it works. hope this clears up a bit.

+2


source







All Articles