How to create a Horizontal Navigation Bar in HTML and CSS?
To create a Horizontal Navigation Bar in HTML and CSS, use an unordered list (<ul>) for navigation items, styled with CSS to display horizontally. Setlist items (<li>) to inline or inline-block, applying styles for layout, spacing, and appearance to achieve desired design and functionality.
Approach:
- First, create a <nav> element with <ul> and <li> for navigation links.
- Use CSS flex for a horizontal layout, sticky positioning, and background styling.
- Apply styling for text color, spacing, and alignment.
- Add hover effects to enhance interactivity, like changing link colors.
- Include optional elements (e.g., search bar) and style for consistency.
- Consider media queries for responsiveness, and adjusting styles for different screen sizes.
Example: In this example, we will create a horizontal navigation bar using HTML and CSS.
<!DOCTYPE html>
<html>
<head>
<title>Building a Horizontal Navigation Bar</title>
<style>
* {
margin: 0;
padding: 0;
}
body {
font-family: 'Arial', sans-serif;
}
.navbar {
display: flex;
position: sticky;
align-items: center;
justify-content: space-between;
top: 0px;
background: rgba(0, 0, 0, 0.6) url(
'https://media.w3wiki.net/wp-content/uploads/20201215124609/Capture-300x14.PNG');
background-blend-mode: darken;
background-size: cover;
color: white;
padding: 10px 20px;
}
.nav-list {
display: flex;
list-style: none;
}
.nav-list li {
margin-right: 20px;
}
.nav-list li:last-child {
margin-right: 0;
}
.nav-list li a {
text-decoration: none;
color: white;
font-size: 18px;
transition: color 0.3s ease-in-out;
}
.nav-list li a:hover {
color: #ffd700;
/* Change the color on hover */
}
.rightNav {
text-align: right;
}
#search {
padding: 8px;
font-size: 16px;
border: 2px solid #fff;
border-radius: 5px;
}
.btn {
background-color: #ffd700;
color: #000;
border: none;
padding: 8px 12px;
border-radius: 5px;
cursor: pointer;
transition: background-color 0.3s ease-in-out;
}
.btn:hover {
background-color: #000;
/* Change the background color on hover */
color: #ffd700;
}
</style>
</head>
<body>
<nav class="navbar">
<ul class="nav-list">
<li><a href="#home">Home</a></li>
<li><a href="#about">About Us</a></li>
<li><a href="#services">Services</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
<div class="rightNav">
<input type="text"
name="search"
id="search"
placeholder="Search">
<button class="btn btn-sm">Search</button>
</div>
</nav>
</body>
</html>
Output: