Home > Enterprise >  navbar items shaking on hover
navbar items shaking on hover

Time:04-01

I am new to learning web designing. I am creating a sample website for my practice. I am stuck on the navbar item issue. after adding a hover effect on list items my items start shaking when I hover on them.

Here is my code:

<nav>
            <div>
            </div>
            <ul>
                <li><a>one</a></li>
                <li><a>two</a></li>
                <li><a>three</a></li>
            </ul>
        </nav>

CSS style:

nav {
    display: flex;
    justify-content: space-around;
    flex-direction: row;
    align-content: center;
    align-items: center;
    width: 100%;
    background-color: #a33454;
}

nav div {
    height: 60px;
    width: 150px;
    margin: 0.5rem;
}

nav ul {
    display: flex;
    list-style: none;
    justify-content: space-between;
    margin: 0.5rem;
    align-items: center;
    align-content: center;
}

nav ul li {
    font-size: 1.3rem;
    padding: 0.5rem;
    margin: 0.2rem 0.6rem;
}

nav ul li:hover{
    border-bottom: 4px solid #022222;
}

I also created a sandbox demo

CodePudding user response:

This is happening due to the border-bottom which appears when hovering. That is adding 4px to the height.

The best way around it is to also have a border in the not-hovered state but make it invisible.

nav ul li {
    font-size: 1.3rem;
    padding: 0.5rem;
    margin: 0.2rem 0.6rem;
    border-bottom: 4px solid transparent;
}

nav ul li:hover{
    border-bottom: 4px solid #022222;
}

By setting color to transparent, it will be invisible.

CodePudding user response:

This is because border-bottom actually increases the content box size with 4px. Read more: https://www.w3schools.com/css/css_boxmodel.asp

You can use the pseudo-element ::after to make a 4px line under the li-element like so:

nav {
  display: flex;
  justify-content: space-around;
  flex-direction: row;
  align-content: center;
  align-items: center;
  width: 100%;
  background-color: #a33454;
}

nav div {
  margin: 0.5rem;
}

nav div {
  height: 60px;
  width: 150px;
}

nav ul {
  display: flex;
  list-style: none;
  justify-content: space-between;
  margin: 0.5rem;
  align-items: center;
  align-content: center;
}

nav ul li {
  font-size: 1.3rem;
  padding: 0.5rem;
  margin: 0.2rem 0.6rem;
  position: relative;
}

nav ul li::after {
  content: '';
  display: none;
  position: absolute;
  color: #022222;
  background-color: #022222;
  height: 4px;
  width: 100%;
  bottom: 0;
  left: 0;
}

nav ul li:hover::after {
  display: block;
}
<header>
  <nav>
    <div>
    </div>
    <ul>
      <li><a>one</a></li>
      <li><a>two</a></li>
      <li><a>three</a></li>
    </ul>
  </nav>
  <div >

  </div>
</header>

By giving it width: 100% and height: 4px;, the pseudo-element will have the full width of the li-element and also the specified 4px height.

  • Related