I have an outer div id='a'
and an inner div id='b'
.
<div id="a">
<div id="b">hey</div>
</div>
After I set the outer div position to absolute
and reposition it, the inner div returns 0
for offsetLeft
. But since setting left ="30vw"
makes it farther from the left, I would expect it to be a larger number now, not 0
.
const inner = document.getElementById("b");
const outer = document.getElementById("a");
console.log("offsetLeft of inner start: " inner.offsetLeft);
// logging >> offsetLeft of inner start: 8
outer.style.position = "absolute";
outer.style.left = "30vw";
console.log("offsetLeft of inner: " inner.offsetLeft);
// logging >> offsetLeft of inner: 0
How do I get the actual pixels from the left?
CodePudding user response:
The offsetLeft
"returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node." So, if you move the outer
, a change for the inner
is not expected, since it is relative to the parent, in this case the outer
.
To get the actual pixels from the left you can use the offsetLeft
of the outer
, like:
console.log("Actual pixels: " outer.offsetLeft);
CodePudding user response:
offsetLeft
is relative to the HTMLElement object's offsetParent
. The offsetParent
of an element is its closest ancestor whose CSS position
isn't static
, or which creates a new containing block.
Until outer
has its position
set, inner
's offsetParent
is the <body>
element, and so inner
's offsetLeft
is relative to it:
const inner = document.getElementById("b");
const outer = document.getElementById("a");
console.log("offsetParent of inner start: ", inner.offsetParent);
outer.style.position = "absolute";
console.log("offsetParent of inner: ", inner.offsetParent);
<div id="a">
<div id="b">hey</div>
</div>
If you want to have the position relative to the viewport instead, then use getBoundingClientRect()
.
const inner = document.getElementById("b");
const outer = document.getElementById("a");
console.log("gBCR.left of inner start: " inner.offsetLeft);
// logging >> offsetLeft of inner start: 8
outer.style.position = "absolute";
outer.style.left = "30vw";
console.log("gBCR.left of inner: " inner.getBoundingClientRect().left);
// logging >> offsetLeft of inner: 0
<div id="a">
<div id="b">hey</div>
</div>