gaurav gupta gaurav gupta - 4 months ago 8
CSS Question

How to find the offset of a relatively positioned element

I am not able to find the offsets (so called) of a html element if its parent has a relative positioning.


This jsFiddle explains my problem:

https://jsfiddle.net/10hexdt1/




var content = document.getElementById('content');
var canvas = document.getElementById('canvas');

// CASE 1
console.log(canvas.offsetTop,canvas.offsetLeft);

// CASE 2
content.style.position = 'relative';
console.log(canvas.offsetTop,canvas.offsetLeft);

console.log('how do i get "offsets" in second case?');

#app {
background:yellow;
padding:20px;
}

#content {
height:200px;
width:100%;
}

#canvas {
height:100%;
width:100%;
background:green;
}

<div id="app">
<h1>Problem !</h1>
<div id="content">
<div id="canvas">

</div>
</div>
</div>




Answer

Initially, the offsetParent of the canvas is the document.body, and all offset* properties are based on that.

When this is executed:

content.style.position = 'relative';

content becomes the canvas's offsetParent.

If you want to keep the offsets relative to document.body, use getBoundingClientRect():

console.log(canvas.getBoundingClientRect().top, canvas.getBoundingClientRect().left);

var content = document.getElementById('content');
var canvas = document.getElementById('canvas');

// CASE 1
console.log(canvas.offsetTop,canvas.offsetLeft);

// CASE 2
content.style.position = 'relative';
console.log(canvas.getBoundingClientRect().top, canvas.getBoundingClientRect().left);
#app {
  background:yellow;
  padding:20px;
}

#content {
  height:200px;
  width:100%;
}

#canvas {
  height:100%;
  width:100%;
  background:green;
}
<div id="app">
  <h1>Problem !</h1>
  <div id="content">
    <div id="canvas">

    </div>
  </div>
</div>