I want to position a div relative to other elements on the page.
This 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 needed, I execute the following code:
let p = puz.getBoundingClientRect(); let s = getelem("success"); s.style.left = p.left; s.style.top = p.top; s.style.display = "block";
turn out:
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)
Looks like this:
The issue is: Why is s.top different from p.top?
P粉6355097192024-04-05 11:02:56
#success is absolutely positioned, so the flow of other elements in the DOM will not affect its positioning, while attributes such as top
will affect its positioning, and the position of #puzzle is static
(default) and not affected by top
and similar, but suitable for document flow.
Fromhttps://www.w3schools.com/Css/css_positioning.asp
If you want #success to be in the top left corner of the #puzzle, you can set position:relative
on the #puzzle and make sure it is the parent of #success in the HTML.