Sajib Biswas Sajib Biswas - 1 month ago 9
CSS Question

How to get values of left/right/top/bottom properties in pixel using javascript?

I need to get the left/right/top/bottom property of the

#test
in
px
. My js code giving the property value as
auto
. How to get the value in
px
?

<div id="test">
<p>Dummy text</p>
</div>


#test{
position: absolute;
}


window.onload = function(){
var test = document.getElementById("test");
var left = window.getComputedStyle(test).getPropertyValue("left");
console.log(left); // auto
};

Answer

Use this code

window.onload = function(){
  var test = document.getElementById("test");
  
  var left = test.offsetLeft;
  var right = test.offsetWidth - left;
  var top = test.offsetTop;
  var bottom = test.offsetHeight - top;
  
  document.write("Left:" + left + "//"); 
  document.write("Right:" + right + "//"); 
  document.write("Top:" + top + "//");
  document.write("Bottom:" + bottom);
};
#test{
    position: absolute;
}
<div id="test">
    <p>Dummy text</p>
</div>