Signup/Sign In

How to fix header in HTML?

HTML headers are used to add heading to the webpage. A heading may contain the website brand name, some logos, or a navigational menu. It is generally placed at top of the page.

These headers are not fixed but we can fix them to a particular position on the viewport. To do so, we need CSS.

Fixing header Using CSS

To fix the position of the header in the webpage, use position: fixed, and to fix it at top use to top:0. The fixed-top can overlay other elements. So to avoid it add margin-top to the other contents.

Example: Create a fixed header in HTML

Here in this example, we have simply added CSS property position: fixed along with top: 0 to fix the header to the top of the page.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>HTML</title>
<style>
  .header {
    position:fixed;
	width: 100%;
	height: 70px;
	background-color: #cccccc;
	text-align : center;
	top: 0;
	  }
   .container {
     margin-top: 50px;
   }
</style>
</head>
<body>
	<div class="header">
	  <h1>Fixed Header</h1>
    </div>
	<div class="container">
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	  <h3>Scroll here to see effect</h3>  
	</div>
</body>
</html>

Output

Fixed header

Example: Create a fixed navigation header

In this example, we will be adding a navbar to the header and place it fixed to the top of the viewport.

Conclusion

The headers in HTML can be fixed using CSS position properties. We have fixed the header to the top of the viewport. Also, add some margins to the body content so that the header does not overlay with body contents.



About the author: