You can achieve the desired behavior using only HTML and CSS by utilizing the CSS position: sticky property on the header element, instead of using a fixed position header. This will allow the header to behave as a fixed position header when scrolling, but will also allow other elements on the page to take its height into account when calculating scroll positions.
Here's an example:
HTML:
<header class="sticky-header">
<!-- Header content here -->
</header>
<main>
<section id="section1">
<!-- Content for section 1 -->
</section>
<section id="section2">
<!-- Content for section 2 -->
</section>
<section id="section3">
<!-- Content for section 3 -->
</section>
</main>
CSS:
.sticky-header {
position: sticky;
top: 0;
z-index: 100;
background-color: white;
}
section {
padding-top: 100px; /* Adjust this value to match the height of the header */
}
In this example, the header has the sticky-header class, which applies the position: sticky property and sets its top position to 0. The header will behave as a fixed header when scrolling, but the other sections will have a top padding equal to the header's height, allowing them to take its space into account when calculating scroll positions.
By using this approach, you won't need to use JavaScript to adjust the positioning of elements on the page when scrolling. Instead, the browser will handle the positioning automatically based on the CSS properties you've set.
Keep in mind that the position: sticky property has some limitations, such as limited browser support. If you need to support older browsers, you might need to use JavaScript or a polyfill. However, modern browsers generally support the position: sticky property without issues. You can check the current browser support here: https://caniuse.com/?search=position%3A%20sticky