Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get offsetLeft of pseudo elements using javascript

Is there a way to get the offsetLeft of a pseudo element using only javascript ?

I am able to inspect the ::before element through the chrome devtools console and get its offsetLeft.

As window.getComputedStyle(elem, ':before') gives the computed styles for ::before, is there something similar to access the offsetLeft ?

like image 547
vin Avatar asked Jul 03 '26 05:07

vin


1 Answers

You probably already figured this out, but I stumbled on this question looking for the answer myself, and I'm pretty confident that the answer is no. Not without some hacky workarounds, at least.

Over here someone wanting the fully CSS-transformed height of a pseudo element used window.getComputedStyle() to pull all the styles off, slap them on a real element, and then access the bounding rect of that.

But since we're only needing the untransformed position in the viewport, we may not need all that. If it's absolutely positioned within its parent, would be enough to just grab its parent's offsetLeft, then offset that with getComputedStyle to get the real thing:

var pseudoStyles = window.getComputedStyle(parent, ":before");
var pseudoOffsetLeft = parent.offsetLeft + parseFloat(pseudoStyles.left) + "px"

https://jsfiddle.net/4q5uy2af/

It's not as good as getBoundingClientRect since it doesn't take into account CSS transforms, but offsetLeft doesn't do that anyway. And if the pseudo element has position: fixed, the offsetLeft can be calculated purely from the styles. If the browser's still in control of placing it in the flow, though, I think things get trickier. You can copy the styles to a real element, but you'll need to hide the pseudo element while you're examining its stand-in's offsetLeft.

like image 181
Different55 Avatar answered Jul 05 '26 17:07

Different55



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!