From my point of view, it would be x: 20
and y: 10
, since there is an offset of 20px na horizontal
and 10px na vertical
.
In any case, you can use the getBoundingClientRect
method to get the position of both, then calculate the difference using the values of top
and left
Remembering that for margem
to be calculated correctly, the parent element must have overflow
set.
var boxPrincipal = document.querySelector(".boxPrincipal");
var elementoSecundario = document.querySelector(".elementoSecundario");
var boundaries = {
principal: boxPrincipal.getBoundingClientRect(),
secundario: elementoSecundario.getBoundingClientRect()
}
console.log({
x: boundaries.secundario.top - boundaries.principal.top,
y: boundaries.secundario.left - boundaries.principal.left,
})
.boxPrincipal {
overflow: hidden;
background-color: teal;
}
.elementoSecundario {
width:100px;
height:80px;
margin-top:10px;
margin-left: 20px;
background-color: purple;
}
.boxQualquer {
margin-top: 30px;
width:50px;
height:50px;
background-color: orange;
}
<div class="boxQualquer"></div>
<div class="boxPrincipal">
<div class="elementoSecundario">
Conteúdo
</div>
</div>
On the other hand, if you want only the distance between the child element and the parent, you can use the properties offsetTop
and offsetLeft
.
For the example below, the value of% of parent% must be position
, relative
or absolute
.
var elementoSecundario = document.querySelector(".elementoSecundario");
console.log({
x: elementoSecundario.offsetTop,
y: elementoSecundario.offsetLeft,
})
.boxPrincipal {
position: relative;
overflow: hidden;
background-color: teal;
}
.elementoSecundario {
width:100px;
height:80px;
margin-top:10px;
margin-left: 20px;
background-color: purple;
}
.boxQualquer {
margin-top: 30px;
width:50px;
height:50px;
background-color: orange;
}
<div class="boxQualquer"></div>
<div class="boxPrincipal">
<div class="elementoSecundario">
Conteúdo
</div>
</div>