Home > Back-end >  Difficulty positioning a div
Difficulty positioning a div

Time:12-27

I want to place a div relative to other elements on the page.

Here is the initial CSS:

#puzzle
{
 display:inline-block;
 vertical-align: top;

 (position: static;)
}

#success
{
 display: none;
 position: absolute;
 top: 235px;
 left: 130px;
 border: 3px solid blue;
 border-radius:25px;
 color: blue;
 background-color: #cfd;
 text-align:center;
 padding:40px;
 font-size:20pt;
}

When desired, I execute this code:

let p = puz.getBoundingClientRect();
let s = getelem("success");
s.style.left = p.left;
s.style.top = p.top;
s.style.display = "block";

And the result is:

puz.getBoundingClientRect()
DOMRect { x: 38, y: 183, ... }

document.getElementById("success").getBoundingClientRect()
DOMRect { x: 38, y: 33.833 ... }

(X and Y are synonyms for Left and Top)

Which looks like this:

The question is: Why is s.top different from p.top?

CodePudding user response:

#success is positioned absolutely, so the flow of the other elements in the DOM do not impact its positioning and properties like top impact its positioning, whereas #puzzle has position static (the default), and is not impacted by top and the like but is fitted into the document flow.

From https://www.w3schools.com/Css/css_positioning.asp

HTML elements are positioned static by default.

Static positioned elements are not affected by the top, bottom, left, and right properties.

An element with position: static; is not positioned in any special way; it is always positioned according to the normal flow of the page:

If you want #success to be positioned within the #puzzle at its top left corner, you can set position: relative on #puzzle and ensure it's a parent to #success in the HTML.

  • Related