Anas Houari
Anas Houari

Reputation: 177

how to specify a div's position as absolute and relative at the same time

I'm new here and I want to know how to specify a div's position as absolute and relative at the same time, Because a div can be a child and parent simultaneously . Thank you for your help

Upvotes: 9

Views: 18115

Answers (3)

Paulie_D
Paulie_D

Reputation: 115047

If the child is positioned absolutely, any grandchild can be again positioned absolutely in relation to the child.

That is, the child does not need to have position:relative for the grandchild to be positioned absolutely in relation to it.

So the child could be considered to have position:absolute for it's own positioning but also "relative" as it also forms the reference point for the positioning of the grandchild.

<div class="parent">
   <div class="child">
      <div class="g-child"></div>
   </div>
</div>
.parent {
   width: 350px;
   height: 350px;
   background: rebeccapurple;
   margin: 1em auto;
   position: relative;
}
    
.child {
   position: absolute;
   width: 50px;
   height: 50px;
   right: 50px;
   top: 50px;
   background: orange;
}
    
.g-child {
   position: absolute;
   width: 25px;
   height: 25px;
   background: #f00;
   top:125%;
   right: 0;
}

Codepen demo

Upvotes: 32

Aron Malkine
Aron Malkine

Reputation: 1

If you require some benefit of absolute positioning (to escape an ancestors overflow for example) but also take up space in the page flow, one trick I use is to duplicate the content inline but then set 'visibility: hidden;' on the inline content so only the absolute item is visible.

Upvotes: 0

Nadia Cerezo
Nadia Cerezo

Reputation: 602

There are several ways to position an HTML block. If you position it as fixed then it will ignore other blocks and position itself in the browser window. If you position it as static (or don't position it at all, 'cause that is the default) then it will move along the flow of the page. If you position it as relative, then you're moving it from its "normal" place (according to the page's flow). If you position it as absolute, then you're positioning it relative to its closest ancestor which is fixed or 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. I fail to see how it can be both.

Upvotes: -1

Related Questions