1

I have the below html:

<body>
    <div class="div1">
    </div>
    <div class="div2">
    </div>
</body>

It has the following style sheet applied to it:

.div1{
    width: 100px;
    height: 100px;
    background-color: orange;
    position: relative;
}

.div2{
    width: 100px;
    height: 100px;
    background-color: blue;
    position: absolute;
}

My understanding from W3Schools is that an absolute positioned element is positioned relative to the nearest positioned ancestor, however if an absolute positioned element has no positioned ancestors, it uses the document body, and moves along with page scrolling.

Shouldn't div2 therefore sit on top of div1 rather than beneath it?

nish91
  • 143
  • 5
  • 2
    It will not move from its 'natural' position unless you explicitly specify where you want it to be, and those coordinates will be from the top left corner of the body. However, if you don't specify coordinates and add another div1 styled div below, that one will end up under div2 – Nadia Chibrikova Nov 22 '20 at 16:42

1 Answers1

1

absolute

The element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top, right, bottom, and left. ----Source from MDN.

You need to specify the position of the div2 using at least one of the values(top,right,bottom or left).

If you wanted the div2 to be positioned on the top left of the page, change the code to:

.div1{
    width: 100px;
    height: 100px;
    background-color: orange;
    position: relative;
}

.div2{
    width: 100px;
    height: 100px;
    background-color: blue;
    position: absolute;
    top: 0;
    left: 0;
}
xqq
  • 11
  • 2