Tips for resolving issues with the header and scrolling content

I am new to CSS and I understand that it is quite simple:

Question: I have a sample HTML page below, and when I scroll the page, the header does not stay fixed in one place. What am I missing here? Please assist.

window.onscroll = function() {
  myFunction()
};

var heading = document.getElementById("myHeading");
var sticky = heading.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    heading.classList.add("sticky");
  } else {
    heading.classList.remove("sticky");
  }
}
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.top-container {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}
<div class="header" id="myHeader">
  <h2>TEST</h2>
</div>
<form id="form1" runat="server">
  <div class="" style="margin-top:2%;position:relative">
    <div class="">
      <span class="sectionHeader">Section A</span>
      <p style="margin-top: 24% !important;margin-bottom: -22% !important;margin-left: 2%;position:relative;">Section B</p>

      ome text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et.
      Inciderint efficiant his ad....

Answer №1

To style the css class ".sticky," you need to add a property like position: fixed;

window.onscroll = function() {
  myFunction()
};

var header = document.getElementById("myHeader");
var sticky = header.offsetTop;

function myFunction() {
  if (window.pageYOffset > sticky) {
    header.classList.add("sticky");
  } else {
    header.classList.remove("sticky");
  }
}
body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.top-container {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}

.sticky { 
  position: fixed;
  top: 0; left: 0;
  width: 100%;
  z-index: 100;
}
<div class="header" id="myHeader">
  <h2>TEST</h2>
</div>
<form id="form1" runat="server">
  <div class="" style="margin-top:2%;position:relative">
    <div class="">
      <span class="sectionHeader">Section A</span>
      <p style="margin-top: 24% !important;margin-bottom: -22% !important;margin-left: 2%;position:relative;">Section B</p>

      ome text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur
      his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert
      laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae
      gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque
      et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet,
      illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus.
      <div>
        <p style="margin-top:45%;margin-bottom:-43% !important;margin-left:2%;">
          Section C
        </p>
        ome text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur
        his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert
        laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae
        gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem ipsum dolor sit amet, illum definitiones no quo, maluisset
        concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae voluptatibus. Some text to enable scrolling.. Lorem
        ipsum dolor sit amet, illum definitiones no quo, maluisset concludaturque et eum, altera fabulas ut quo. Atqui causae gloriatur ius te, id agam omnis evertitur eum. Affert laboramus repudiandae nec et. Inciderint efficiantur his ad. Eum no molestiae
        voluptatibus.
      </div>
    </div>
  </div>
</form>

Answer №2

Make sure to include the following code in your HTML and CSS files:

body {
  margin: 0;
  font-family: Arial, Helvetica, sans-serif;
}

.top-container {
  background-color: #f1f1f1;
  padding: 30px;
  text-align: center;
}

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
  position: fixed;
    width: -webkit-fill-available;
    padding-bottom: 0;
    top: 0;   
}
.form{
   padding-top:10%;
}
<form id="form1" class="form" runat="server"  >

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to display a mySQL database in an HTML div table?

Showcasing the grades in a table format: username assignment weight mark a a1 10% 50% b a1 10% 60% Can this be achieved using PHP/HTML? <div class="a"> <div class="divTabl ...

Is there a way to update the Angular component tag after it has been rendered?

Imagine we have a component in Angular with the selector "grid". @Component({ selector: 'grid', template: '<div>This is a grid.</div>', styleUrls: ['./grid.component.scss'] }) Now, when we include this gri ...

Despite locating the button, Protractor still encounters difficulties when attempting to click on it

I've been having trouble clicking on a button using Protractor. The issue is that even though the driver can locate the element, it still won't click on it. Any assistance would be greatly appreciated. Thank you in advance. Here is the HTML for ...

Selecting one, multiple, or all checkboxes and attempting to proceed by activating the button will not function as intended

The functionality of the "check all" / "uncheck all" button allows me to easily select or deselect all checkboxes within my form. The "proceed..." button should become active once one, multiple, or all checkboxes are checked. While this feature works smoo ...

Center and left-align elements

I want to make my list items align like the dropdown menu shown at the bottom of the picture. The items in the dropdown are centered and aligned vertically in a single line. How can I achieve this effect? Below is the code snippet I am using: <div c ...

Tips for positioning an image at the center of a div element

How can I properly center an image in the middle of a div? <div class="main"> <img...> </div> In the code snippet below, the image is centered, but not perfectly in the middle. https://jsfiddle.net/web_garaux/tng7db0k/ ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...

Optimal arrangement for z-index and opacity

In my design, I have placed a nested link within two absolutely positioned divs structured like this: <div class="container"> <div class="leftPostHolder"> <div class="leftPost"> <h3><a href="#">link ...

Using the contents of a text file as text in an HTML document

I've come up with a clever time-saving trick for my website template project. I want to streamline the process of changing large text files by having a separate plain text document that will automatically transfer its contents to a designated paragrap ...

What is the procedure for displaying the complete text for choices on an ionic select button?

On my page, I have included an Ionic select button. The problem is that the options display a long string, and I want them to show the full text without truncating with dot-dot-dot like this: This is how my code looks: <ion-item *ngIf="select == &apos ...

Using WebDriver Selenium to choose an element within a table following another element

The webpage features a user details table with a functionality to delete users. To remove a user, I must select the row based on the username and then click the "Delete" button. The structure of the HTML table is as follows: <table id="tblUsersGrid" ce ...

tips for integrating external javascript in react applications

If you are working on an HTML page, you can include a JavaScript file using the following syntax: <script src="path"></script>. However, when it comes to retrieving variables from an external path in React, things get a bit more complex. For in ...

Change the color when hovering over the select box

Using jQuery, my goal is to change the hover color in a select box from its default blue to red. I understand that the hover color of the select input may vary based on the operating system rather than the browser, but I am making progress towards achievin ...

The Bootstrap nav-tab functions perfectly on a local server, but unfortunately does not work when hosted remotely

UPDATE: Issue resolved so I have removed the Github link. It turns out that Github pages require a secure https connection for all linked scripts. Always remember to check the console! I encountered an unusual bug where the Bootstrap nav-tab functionality ...

Why is it not possible to establish a minimum height of 100% in html?

HTML Code: <!DOCTYPE html> <html> <head></head> <body> <link rel="stylesheet" type="text/css" href="style.css"> <div class="sheet" style="width:80%;max-width:1024px;height:400px;"></div> ...

Is there a way to tally up the number of green items and display a <p> tag when every item has been marked green?

I have created a checklist that includes checkboxes. I am looking to display some text when all the checkboxes are checked and green. Can someone assist me with writing the code for this functionality? $(document).ready(function() { $("i").click(funct ...

Bootstrap 4 alert boxes extend the text to span the entire width of the alert

How can I make the paragraph text span across most of the box width in Bootstrap 4? <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJ ...

Why is object-fit not functioning properly? Could it be that the container is influencing the object-fit

Why isn't object-fit working? It only seems to work with inline styling in the image tag. Could it be the hero_media container affecting object-fit? I'm also attempting to use pseudo-elements (after and before) to add text to the image. Is it nec ...

Pass information from JavaScript to PHP without using a form

I am trying to pass data from JavaScript to PHP without using an HTML form. The scenario involves the user clicking on a specific HTML div, sending its ID to a JavaScript file, and then transferring it back to a PHP file. How can I achieve this? Below is ...

Prevent floating labels from reverting to their initial position

Issue with Form Labels I am currently in the process of creating a login form that utilizes labels as placeholders. The reason for this choice is because the labels will need to be translated and our JavaScript cannot target the placeholder text or our de ...