Scroll inner div without scrolling outer parent div

75 views Asked by At

How can I set some element in the inner div to scroll into view without scrolling the parent element? In the following example (I added some delay so the effect is more easily seen) you can see how the parent div scrolls even when it isn't needed for the target element to be scrolled into view by using just the inner div scroll.

setTimeout(() => document.getElementById("target").scrollIntoView({
  behavior: "smooth",
  block: "nearest",
}), 1000)
body {
  font-family: sans-serif;
}

.outer {
  border: 1px solid;
  height: 10em;
  overflow: auto;
}

.inner {
  border: 1px solid blue;
  height: 5em;
  overflow: auto;
}
<body>
  <div class="outer">
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
    <div class="inner">
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div id="target">Scroll me</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>
      <div>Something else</div>

    </div>
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
    <div>Something</div>
  </div>
</body>

This is a simplified example to show the problem I want to solve by using pure js/css (my app uses react without any styling library added)

0

There are 0 answers