Search code examples
js-scrollintoview

wield behavior of Element.scrollIntoView()


I'm using Element.scrollIntoView(). The scrolling is working, but it breaks the layout of my whole page at the same time. Following is the demo:

* {
  margin: 0;
  padding: 0;
}

html, body {
  width: 100%;
  height: 100%;
}

.content {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  background-color: lightgray;
}

ul {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  bottom: 0;
  background-color: gray;
  overflow-y: scroll;
}

li {
  list-style: none;
}

#div {
  position: absolute;
  width: 100%;
  height: 300px;
  left: 0;
  bottom: -300px;
  background-color: darkgray;
}

button {
  position: absolute;
  right: 0;
  bottom: 0;
}
<div class=content>
  <!-- it's the ul to scroll, staying at the bottom of the page -->
  <ul>
    <li id=li>abc</li>
    <li>def</li>
  </ul>
  <!-- it's the div hidden under the bottom edge of the page -->
  <div id=div>i should stay hidden.</div>
  <button onclick=li.scrollIntoView();>scrollIntoView</button>
</div>

I hide a <div> under the bottom edge of the page. When I scrollIntoView the 1st <li> in <ul>, the hidden <div> is pulled out. Not only the <div>, the whole content of the page is pulled up for 300px.

I expect it to simply scroll the <li> into view of <ul>. Why is it affecting the layout of the whole page?


Solution

  • I think I find the answer myself. See this answer. It's about anchors, but scrollIntoView share the same mechanism internally I think.

    The browser will try best to ensure the element is visible. When it's in a container, it will first scroll the container to a position with best visibility, so the contents are pulled up.