How to subtract pixels from an elements current position using only JavaScript?

Without using jQuery, is there a way to get an element’s current position and add/subtract from it? Let’s say an element has this CSS

position: relative;
top: 400px;
/*400px away from the top*/

Can JavaScript get the amount of pixels from “top” and subtract from it? I know that I can directly edit the top property with document.getElementById(“element”) , but I want to get the value itself first, then subtract a number of pixels from that value, and then put the new value as the position. Is this possible?


Yes you need to get the computedStyle of the element let rect = getComputedStyle('el'), assign this to a variable then you can use the top position to get amount set in your class => will give you the top position.

const cont = document.querySelector('.cont')

function getTopPos(el){
  // get the computed style of element
  // get the top position using .top
  // split at px and get the first index which will be the number
  // subtract it by desired amount and concatenate px measurement back to the value
  let was = getComputedStyle(el).top; = `${getComputedStyle(el).top.split('px')[0] - 300}px`
  console.log(`top position is now: ${getComputedStyle(el).top.split('px')[0]}px, was: ${was}`)

* {
  margin: 0;
  padding: 0;

.cont {
  width: 100px;
  height: 100px;
  background: red;
  position: relative;
  top: 400px;
<div class="cont">Was 400 pixels from top, now 100 pixels from top</div>