Bài này mình sẽ hướng dẫn bạn cách làm menu off canvas trong Bootstrap 4 thay cho menu truyền thống dropdown của bootstrap.
HTML
<nav class="navbar navbar-expand-md navbar-dark bg-dark">
<a class="navbar-brand" href="#">Lar.vn</a>
<button class="navbar-toggler p-0 border-0" type="button" data-toggle="offcanvas">
<span class="navbar-toggler-icon"></span>
</button>
<div class="navbar-collapse offcanvas-collapse">
<ul class="navbar-nav mr-auto">
<li class="nav-item active">
<a class="nav-link" href="#">Trang chủ <span class="sr-only">(current)</span></a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Giới thiệu</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Dự án</a>
</li>
<li class="nav-item">
<a class="nav-link" href="#">Dịch vụ</a>
</li>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="http://example.com" id="dropdown01" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">Sản phẩm</a>
<div class="dropdown-menu" aria-labelledby="dropdown01">
<a class="dropdown-item" href="#">PHP</a>
<a class="dropdown-item" href="#">Laravel</a>
<a class="dropdown-item" href="#">Phalcon</a>
</div>
</li>
</ul>
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" placeholder="..." aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit">Tìm kiếm</button>
</form>
</div>
</nav>
Các bạn nên lưu ý vị trí đặt class
CSS
html,
body {
overflow-x: hidden;
}
@media (max-width: 767.98px) {
.offcanvas-collapse {
position: fixed;
top: 56px;
bottom: 0;
width: 100%;
padding-right: 1rem;
padding-left: 1rem;
overflow-y: auto;
background-color: var(--gray-dark);
transition: -webkit-transform .3s ease-in-out;
transition: transform .3s ease-in-out;
transition: transform .3s ease-in-out, -webkit-transform .3s ease-in-out;
-webkit-transform: translateX(100%);
transform: translateX(100%);
}
.offcanvas-collapse.open {
-webkit-transform: translateX(-1rem);
transform: translateX(-1rem);
}
}
JS
$(function () {
$('[data-toggle="offcanvas"]').on('click', function () {
$('.offcanvas-collapse').toggleClass('open')
})
})
Tải code:
offcanvas-lar.vn
Cám ơn bạn đã đọc bài