CSS Responsive Navigation Bar (Horizontal Menus)

We will use CSS media queries to create a responsive top navigation. It changes the shape, size, position etc. of the horizontal menu, depending on screen sizes.

Responsive Horizontal Menu

This example use media queries to stack the topnav vertically when the screen size is 600px or less.

media queries are CSS styles, that is applied to the same elements, depending on screen sizes.

Resize the Browser to see the effect.

Example

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {margin: 0;}

ul.topnav {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
background-color: #333;
}

ul.topnav li {float: left;}

ul.topnav li a {
display: block;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}

ul.topnav li a:hover:not(.active) {background-color: #111;}

ul.topnav li a.active {background-color: #0054ff;}

ul.topnav li.right {float: right;}

@media screen and (max-width: 600px) {
ul.topnav li.right,
ul.topnav li {float: none;}
}
</style>
</head>
<body>

<ul class="topnav">
<li><a class="active" href="#home">Home</a></li>
<li><a href="#news">News</a></li>
<li><a href="#contact">Contact</a></li>
<li class="right"><a href="#about">About</a></li>
</ul>

<div style="padding:0 16px;">
<h2>Responsive Topnav Example</h2>
<p>This example use media queries to stack the topnav vertically when the screen size is 600px or less.</p>
<p>You will learn more about media queries and responsive web design later in our CSS Tutorial.</p>
<h4>Resize the browser window to see the effect.</h4>
</div>

</body>
</html>

Example Explained

  • <meta name="viewport" content="width=device-width, initial-scale=1.0"> - This Sets the viewport to the same as device width.
  • @media screen and (max-width: 600px)
    • @media screen - This select screen as its input i.e. the change in the width of the screen will use this media query.
    • and (max-width: 600px) - This select screen with its width less than 600px as its input i.e. the change in the width of the screen will use this media query.

Comments