Bootstrap FreeKB - HTML - Top navigation bar
HTML - Top navigation bar

Updated:   |  HTML articles

The following HTML top navigation bar will fit to any device (from a smart phone to a large PC monitor), be fixed to the top of the page, and scale based on device width. Fancy!

In <head> tags, set the viewport width to the width of the device.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

 

Use the following CSS for the navbar.

.navbar {
	overflow: hidden;
	position: fixed;
	top: 0;
	width: 100%;
	background: #eeeeee;
	border-top: 1px solid #ccc;
	border-bottom: 2px solid red;
}

 

Without the following JQuery and JavaScript, content will appear behind the top navigation bar. This JavaScript is used so that content appears below the top navigation bar, regardless of the size of the device being used (pc laptop table mobile). Place the JQuery and JavaScript inside of the <head> tags.

<script src="http://resources.freekb.net/js/jquery-3.2.1.min.js"></script>	
<script>
$(document).ready(function() {
  var contentPlacement = $('#header').position().top + $('#header').height();
  $('#content').css('margin-top',contentPlacement);
});    
</script>

 

You can now create the top navigation bar by using id="header" and class="navbar" in a div tag inside of the <body> tags.

<div id="header" class="navbar">
  Top Nav
</div>

 

Ensure the body margin is set to 0, so that there is no gap between the top navigation bar and the edges of the display. If you are using bootstrap, this is probably already set in your bootstrap CSS.

<body style="margin: 0">

 

You can then place content below the top navigation bar by using id="content" in a div tag.

<div id="content">
  <p>Body Content</p>
  <p>Body Content</p>
  <p>Body Content</p>
  <p>Body Content</p>
</div>

 

This should result in a top navigation bar that is fixed to the top of the page, and the content below the top navigation bar never appears on top of the top navigation bar, and the content is fixed to be below the top navigation bar.




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter e47caf in the box below so that we can be sure you are a human.