Create a responsive navbar with a brand and three links
Description: Build a navbar with the brand “MySite” and three links. It must collapse into a toggle button on small screens.
Hint:
- Use
navbar navbar-expand-md,navbar-togglerandcollapse navbar-collapse.
Solution
<nav class="navbar navbar-expand-md bg-body-tertiary">
<div class="container-fluid">
<a class="navbar-brand" href="#">MySite</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#menu" aria-controls="menu" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="menu">
<ul class="navbar-nav">
<li class="nav-item"><a class="nav-link active" href="#">Home</a></li>
<li class="nav-item"><a class="nav-link" href="#">About</a></li>
<li class="nav-item"><a class="nav-link" href="#">Contact</a></li>
</ul>
</div>
</div>
</nav>
Live preview
document.querySelector('.navbar-toggler').click();
await new Promise(r => setTimeout(r, 600));
console.log('menu opens on a small screen: ' + document.getElementById('menu').classList.contains('show'));
console.log('links in the menu: ' + document.querySelectorAll('#menu .nav-link').length);
Console output (real Chrome)
menu opens on a small screen: true
links in the menu: 3
How it works
- The links are hidden in the
collapsepart, and the toggler button opens them. - From the md breakpoint (768px) the menu is shown in a row.
Read Navbar.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |