I’m using Bootstrap and custom CSS to design a navbar that keeps the shopping cart icon on the right side of the bar on both desktop and mobile. No matter how I order the elements, I can’t seem to do this, and the CSS "order" property doesn’t appear to make a difference.
This is the mobile navbar, which has the desired layout:
Mobile navbar
This is the desktop navbar, which is wrong:
Desktop navbar
Here is my HTML:
<nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light mb-3">
<div class="container">
<button id="nav-toggle" class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target=".navbar-collapse" aria-controls="navbarSupportedContent"
aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<a id="nav-header" class="navbar-brand" asp-area="" asp-page="/Index">
<img alt="Home" src="placeholder.webp" />
</a>
<a id="nav-cart" class="nav-item nav-link text-light" asp-area="" asp-page="/Cart">
<img alt="Cart" src="assets/shopping_cart_25x24.webp" />
</a>
<div id="nav-menu" class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
<ul class="navbar-nav flex-grow-1">
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-page="/Shop">Shop</a>
</li>
<li class="nav-item">
<a class="nav-link text-light" asp-area="" asp-page="/About">About</a>
</li>
</ul>
</div>
</div>
</nav>
Here is my custom CSS that sits on top of Bootstrap:
@media (min-width: 576px) {
nav #nav-cart {
order: 3;
}
nav #nav-menu {
order: 2;
}
.nav-item {
margin-bottom: -4px;
}
}
nav {
background-color: #a8d0b2;
border-bottom: 1px solid #e5e5e5;
box-shadow: 0 .25rem .75rem rgba(0, 0, 0, .05);
flex: auto;
font: lighter 1.5rem 'Buxton Sketch', sans-serif;
}
nav #nav-cart {
order: 2;
}
nav #nav-cart img {
max-height: 32px;
}
nav #nav-header {
order: 1;
}
nav #nav-menu {
order: 3;
}
nav #nav-toggle {
order: 0;
}
.navbar-brand {
font-size: 22px;
white-space: normal;
text-align: center;
word-break: break-all;
}
Am I implementing this incorrectly, or is there something preventing this from behaving as intended?
2
Answers
Everything is fine except that
@media
rules are overridden by a later code so on the desktop screens an order is:#nav-header { order: 1; }
#nav-cart { order: 2; }
#nav-menu { order: 3; }
To prevent this a whole
@media
block should be placed at the end:You need to change your media query to (max-width: 576px , sort of ‘small screen’) and change order outside media query as below