Search code examples
htmlcss

Going directly into my how can i remove the <li> element from the normal document flow when hovered over it without moving it away from its position?


I want to make the text in the li element to move out of the document flow and increase its z-index so that increasing the size of the text does not affect the position and structure of the other elements.

nav {
  display: flex;
  justify-content: space-between;
  margin: 2rem 10px;
  align-items: center;
  padding: 0 5vw;
}

nav div ul {
  list-style: none;
  display: inline-block;
  position: relative;
}

nav div ul li {
  display: inline-block;
  margin: 0.2rem;
  font-size: 0.95rem;
  cursor: pointer;
}

nav div ul li:hover {
  position: absolute;
}

@media(max-width:500px) {
  nav {
    margin: 10px 0;
  }
}
<nav>
  <h3>Writings</h3>
  <div>
    <ul class="nav-links">
      <li>Categories</li>
      <li>Articles</li>
      <li>About</li>
    </ul>
  </div>
</nav>

I have tried position:relative in the ul and position:fixed/absolute in the li on hover but it does not give the required result. The text moves to the side when i want it to stay at its original position and come on top of all the other elements if required.


Solution

  • You can transform with a scale on hover as that does not affect neighboring elements' positions.

    This snippet adds a little transition time to it also, and a background of white so if the text is a little too big and overlaps a neighbor it is clearly seen.

    nav {
      display: flex;
      justify-content: space-between;
      margin: 2rem 10px;
      align-items: center;
      padding: 0 5vw;
    }
    
    nav div ul {
      list-style: none;
      display: inline-block;
      position: relative;
    }
    
    nav div ul li {
      display: inline-block;
      margin: 0.2rem;
      font-size: 0.95rem;
      cursor: pointer;
      transition: transform 0.3s linear;
    }
    
    nav div ul li:hover {
      transform: scale(1.5);
      background: white;
    }
    
    @media(max-width:500px) {
      nav {
        margin: 10px 0;
      }
    }
    <nav>
      <h3>Writings</h3>
      <div>
        <ul class="nav-links">
          <li>Categories</li>
          <li>Articles</li>
          <li>About</li>
        </ul>
      </div>
    </nav>