Get x y position of element relative to parent div Jquery
<p>Given the following markup:</p>

<pre><code>&lt;div class='container'&gt;
  &lt;div class='inner'&gt;
    &lt;div class='target'&gt;&lt;/div&gt;
  &lt;/div&gt;
&lt;/div&gt;
</code></pre>

<p>And styles:</p>

<pre><code>.container {
  width: 100%;
  height: 100vh;
  overflow: scroll;
}

.inner {
  width: 3000px;
  height: 2000px;
}

.target {
  height: 200px;
  width: 200px;
  background: red;
}
</code></pre>

<p>How would I go about scrolling the <code>.container</code> with <code>$('.container').scrollLeft(X)</code> and <code>$('.container').scrollTop(X)</code> to center <code>.target</code> in the middle of the viewport?</p>

<p>I get it to work by playing around with static values but as soon as the size of the screen changes, e.g. on mobile or tablets, then the centering is off.</p>

<p>I've also tried doing:</p>

<pre><code>$('.container').scrollLeft($('.target').position().left);
$('.container').scrollTop($('.target').position().top);
</code></pre>

<p>But this doesn't seem to work, the centering is way off. I dont' know if this is because the <code>.target</code> is contained in a div with <code>overflow: scroll</code>.</p>