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
An element with position: absolute; is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport, like fixed). However; if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.
It is possible to set absolute positioning of a child element relative to the parent container. For that, you must specify the position property with its “relative” value on the parent element. If we don't specify the position of the parent element, the child <div> will be positioned relative to the page.
Note: z-index only works on positioned elements (position: absolute, position: relative, position: fixed, or position: sticky) and flex items (elements that are direct children of display:flex elements).
Absolutely positioned elements are positioned with respect to a containing block, which is the nearest postioned ancestor. If there is no positioned ancestor, the viewport will be the containing block. Elements with fixed positioning are fixed with respect to the viewport—the viewport is always their containing block.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With