Table of Contents
Creating a responsive header for your website is essential for providing a good user experience across all devices. Using CSS Flexbox combined with a hamburger menu allows your site to adapt seamlessly to mobile screens while maintaining a clean and functional design.
Understanding Flexbox for Header Layouts
Flexbox is a powerful CSS layout module that makes it easy to align and distribute space among items in a container. For headers, Flexbox can help position logo, navigation links, and other elements in a flexible, responsive manner.
Designing the Header Structure
Start with a simple HTML structure for your header:
<header class="site-header">
<div class="logo">MySite</div>
<nav class="main-nav">
<ul>
<li><a href="#">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
</nav>
<div class="hamburger">☰</div>
</header>
Styling with CSS Flexbox
Apply CSS styles to make the header elements align horizontally and respond to screen size changes:
.site-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 10px 20px;
background-color: #333;
color: #fff;
}
.logo {
font-size: 1.5em;
font-weight: bold;
}
.main-nav ul {
display: flex;
list-style: none;
margin: 0;
padding: 0;
}
.main-nav li {
margin-left: 20px;
}
.hamburger {
display: none;
font-size: 1.5em;
cursor: pointer;
}
Making the Hamburger Menu Responsive
Use media queries to hide the navigation links on small screens and show the hamburger icon instead:
@media (max-width: 768px) {
.main-nav {
display: none;
}
.hamburger {
display: block;
}
}
Adding Interactivity with JavaScript
Implement a simple script to toggle the menu when the hamburger icon is clicked:
document.querySelector('.hamburger').addEventListener('click', function() {
const nav = document.querySelector('.main-nav');
if (nav.style.display === 'block') {
nav.style.display = 'none';
} else {
nav.style.display = 'block';
}
});
Final Tips for a Responsive Header
Ensure your header is accessible by adding appropriate ARIA labels and keyboard navigation support. Test your design on various devices to confirm responsiveness and usability. Flexbox combined with a hamburger menu creates a sleek, adaptable header that enhances your website’s mobile experience.