Categories
JavaScript Answers

How to Prevent Content from Being Hidden Underneath a Fixed Header by Using the scroll-margin-top CSS Property?

Spread the love

To call the scrollIntoView method to scroll to an element without the fixed position header covering up the element we scrolled into view, we can set the scroll-margin-top CSS property to make sure the element we want to scroll to isn’t covered by the fixed header.

For instance, if we have:

<div style='position: fixed; width: 100vw; background-color: yellow'>
  header
</div>
<div id='content'>

</div>

Then we add the following JavaScript to create the elements and scroll to the one we want:

const content = document.querySelector('#content')
for (const n of Array(200).fill().map((_, i) => i)) {
  const el = document.createElement('p')
  el.id = `el-${n}`
  el.textContent = n
  content.appendChild(el)
}

const node = document.querySelector('#el-150')
node.scrollIntoView(true);

We get the div with ID content with document.querySelector .

Then we have a for-of loop that loops through the numbers created.

In the loop body, we call document.createElement to create the p elements.

And then we set the ID of the element created with:

el.id = `el-${n}`

We set the text content with:

el.textContent = n

And then we append it to the div with:

content.appendChild(el)

Then we select the element we want to scroll and scroll to it by writing:

const node = document.querySelector('#el-150')
node.scrollIntoView(true);

Finally, to make sure the fixed header doesn’t block the element we’re scrolling to, we write:

#el-150 {
  scroll-margin-top: 3rem;
}

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *