I’m trying to implement functionality in my HTML page where clicking a button scrolls to a specific element (#content) while maintaining a certain amount of padding from the top of the viewport. However, my current approach isn’t working as expected.
Here’s my HTML and JavaScript code:
function myFunction() {
const element = document.getElementById("content");
element.scrollIntoView();
setTimeout(() => {
window.scrollBy({
top: -200
});
}, 0);
}
#myDIV {
height: 250px;
width: 250px;
overflow: auto;
background: coral;
}
#content {
margin: 500px;
height: 800px;
width: 2000px;
background-color: coral;
}
<h1>The Element Object</h1>
<h2>The scrollIntoView() Method</h2>
<button onclick="myFunction()">Scroll</button>
<p>Click "Scroll" to scroll to the top of the element with id="content".</p>
<div id="myDIV">
<div id="content">
<p>Some text inside an element.</p>
<p>Some text inside an element.</p>
<p>Some text inside an element.</p>
</div>
</div>
I expect the page to scroll to the #content element while maintaining a 200px padding from the top of the viewport. However, the current implementation doesn’t achieve this effect. How can I modify my code to achieve the desired behavior?
2
Answers
You can use the parent container
scrollTop
to remove200
pixels from itЗастосуйте css властивість
scroll-margin-top
: