In this tutorial, we will create a hamburger menu using HTML, CSS, and JavaScript. A hamburger menu is a common design pattern used in websites and mobile applications to show a navigation menu hidden behind a hamburger icon. When the user clicks on the icon, the menu slides out from the side of the screen, providing access to different pages and sections of the website.
HTML:
First, we need to create the structure of our hamburger menu in HTML. We will create a div element to contain the menu items and a button element for the hamburger icon. Here is the HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Hamburger Menu Tutorial</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="hamburger-menu">
<button class="hamburger-btn">
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</button>
<div class="menu-items">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Contact</a>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
CSS:
Next, we will style our hamburger menu using CSS. We will position the menu items off-screen initially and use CSS transitions to animate them into view when the hamburger icon is clicked. Here is the CSS code:
body {
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
.hamburger-menu {
position: fixed;
top: 0;
right: 0;
padding: 15px;
}
.hamburger-btn {
background: none;
border: none;
cursor: pointer;
}
.bar {
display: block;
width: 25px;
height: 3px;
background: #333;
margin: 5px 0;
}
.menu-items {
display: none;
position: fixed;
top: 0;
right: -200px;
width: 200px;
height: 100%;
background: #f4f4f4;
padding: 20px;
transition: right 0.3s ease;
}
.menu-items a {
display: block;
margin-bottom: 20px;
text-decoration: none;
color: #333;
}
JavaScript:
Finally, we will use JavaScript to toggle the visibility of the menu items when the hamburger icon is clicked. We will add an event listener to the button element that will toggle a CSS class on the menu items div to show or hide them. Here is the JavaScript code:
const menuBtn = document.querySelector('.hamburger-btn');
const menuItems = document.querySelector('.menu-items');
menuBtn.addEventListener('click', () => {
menuItems.classList.toggle('show');
});
That’s it! You have now created a simple hamburger menu using HTML, CSS, and JavaScript. You can further customize the design and functionality of the menu to suit your needs. Happy coding! #shorts
Video Link – https://youtu.be/kuUYuiHpKTo
Buenas, muy mala práctica usar tantos "div", utiliza nav, header, listas, etc… Saludos