Are you tired of the same old static navigation bars? Want to add some flair and interactivity to your website's navigation? Look no further! In this post, we'll explore a cool CSS technique to create an elastic moving active background effect for your navigations that will surely impress your users!
🚀 How does it work?
The concept is to have an elastic background that stretches and contracts to cover the active navigation item as the user hovers over different links. The background will smoothly move and adjust its size to highlight the currently active link.
💻 Example Implementation:
Let's create a simple navigation bar with the elastic moving active background effect using HTML and CSS:
HTML:
<nav>
<ul>
<li><a href="#" class="active">Home</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Services</a></li>
<li><a href="#">Contact</a></li>
</ul>
<div class="elastic-background"></div>
</nav>
CSS:
/* Reset default styles */
body, nav, ul, li, a {
margin: 0;
padding: 0;
list-style: none;
text-decoration: none;
}
nav {
position: relative;
}
ul {
display: flex;
background-color: #f1f1f1;
padding: 8px;
border-radius: 16px;
}
li {
margin: 0 8px;
}
a {
padding: 8px 16px;
color: #333;
border-radius: 16px;
transition: color 0.3s;
}
a:hover {
color: #fff;
background-color: #333;
}
.elastic-background {
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: #333;
border-radius: 16px;
transition: transform 0.3s, width 0.3s;
z-index: -1;
}
a.active ~ .elastic-background {
transform: translateX(0);
}
a {
display: block;
}
a.active {
position: relative;
z-index: 1;
}
🎯 How it works:
- We set up the basic HTML structure with an unordered list (
ul
) representing the navigation items. We also add adiv
with the class.elastic-background
, which will act as our elastic moving background. - The CSS part consists of styling the navigation bar and links. We apply some basic styles to reset default values and style the navigation links.
- The magic happens with the
.elastic-background
class. We position it absolutely, making sure it covers the entire height of the navigation bar. Initially, we set its width to0
so it's not visible. - We use a CSS transition on the
.elastic-background
to smoothly animate thetransform
andwidth
properties. - When a link with the class
.active
is present (corresponding to the currently active page), we apply atransform: translateX(0);
rule to make the elastic background move and cover the active link.