Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

css

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

like image 612
Anas Houari Avatar asked Sep 25 '16 19:09

Anas Houari


People also ask

When you place position absolute on something what is it positioned relative to?

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.

How do you make relative position absolute?

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.

Does Z Index work with position absolute?

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).

How do you use position absolute and fixed?

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.


1 Answers

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

like image 83
Paulie_D Avatar answered Oct 23 '22 22:10

Paulie_D