Home > front end >  Menu with sliding line
Menu with sliding line

Time:03-30

I have a top navbar with links of different width. Currently, whenever a link is clicked it changes its color and adds a bottom border. I want to create a line instead of the bottom border to slide from link to link whenever a new one is selected. Any idea how I can implement such an animation?

CodePudding user response:

I don't think you can achieve the effect with CSS only. Some simple scripting gonna be required. Here's a codepen and the code:

<nav>
  <a>Home</a>
  <a>About</a>
  <a>Our Wonderfull and Usefull Products</a>
  <a>Services</a>
  <a>Contacts</a>
</nav>
nav{
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  
  --decoration-left: 50%;
  --decoration-width: 0;
  
}
nav a{
  padding: .5em .2em;
  margin: 0 1em;
  cursor: pointer;
}
nav::after{
  content: '';
  position: absolute;
  bottom: 0;
  left: var(--decoration-left);
  width: var(--decoration-width);
  height: 4px;
  background: skyblue;
  transition: 300ms;
}
document.addEventListener('DOMContentLoaded',function(){
  
  var nav = document.querySelector('nav');
  nav.addEventListener('mouseover',function(event){
    if( event.target.tagName == 'A' ) {
      nav.style.setProperty(
        '--decoration-left',
        event.target.offsetLeft   'px'
      );
      nav.style.setProperty(
        '--decoration-width',
        event.target.offsetWidth   'px'
      );
    }
  })
  
})

CodePudding user response:

I really can't make out what are you saying but, Do you mean this? :-

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <style>
      *,
      *::after,
      *::before {
        margin: 0;
        padding: 0;
        box-sizing: border-box;
        font-family: "Poppins", sans-serif;
      }

      body {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 100vh;
        background: #111;
      }

      a {
        color: #fff;
        text-decoration: none;
        position: relative;
        font-size: 3rem;
      }

      a::after {
        content: "";
        width: 0%;
        height: 2px;
        border-radius: 99px;
        position: absolute;
        left: 0;
        bottom: 0;
        background: dodgerblue;
        transition: 0.3s ease;
      }

      a:focus::after {
        width: 100%;
      }
    </style>
    <title>Document</title>
  </head>
  <body>
    <a href="#">Something</a>
  </body>
</html>
  • Related