When calling getBoundingClientRect
of a div within an svg in order to position other elements outside of the svg accordingly, the top
and left
values are too high only on Chrome (78.0.3904.108) and Windows 10.
Here is a codepen to demonstrate the problem. The red border around the green box is positioned using the getBoundingClientRect
coordinates of the element within the svg. On Windows Chrome, you'll see the result of the top
and left
values being inflated somehow (first screenshot below). In other browsers it behaves as expected (second screenshot). Is there a better way to achieve this, or is there a reason for why this issue only appears in Windows Chrome?
Update: Adding code snippet.
const svg = document.querySelector('.svg');
const ref = document.querySelector('.ref');
const outer = document.querySelector('.outer');
const refRect = ref.getBoundingClientRect();
console.log('.svg BoundingClientRect', svg.getBoundingClientRect());
console.log('.ref BoundingClientRect', refRect);
$(outer).css('top', refRect.top - window.scrollY)
$(outer).css('left', refRect.left - window.scrollX)
svg {
position: absolute;
top: 0;
left: 0;
width: 200px;
height: 200px;
}
.ref {
background: #ccffcc;
width: 100%;
height: 100%;
}
.outer {
border: 1px solid red;
width: 100px;
height: 100px;
position: fixed;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg class="svg" version="1.1" xmlns="http://www.w3.org/2000/svg">
<foreignObject x="18%" y="14%" width="100" height="100">
<div class="ref">This should be perfectly surrounded by a red border</div>
</foreignObject>
</svg>
<div class="outer"></div>