Roland
Roland

Reputation: 1940

How to make elements stay in place when using transitions on hover

How do I make li elements not move around when applying transitions using :hover? The circles are made applying height and border-radius to the li elements. I've tried making the ul container bigger, but that didn't seem to work. Thanks for your help.

Code:

 body {}
    main {
      display: flex;
      background: #eeeeee;
      min-height: 100vh;
      padding: 1em;
      
    }

    h1 {
      font-family: arial;
      font-size: 1.4em;
      padding-left: 1em;
    }

    ul {
      padding-top:50px;
      min-height: 600px;
      position:relative;

    }

    li {
      position:relative;
      background-color: purple;
      border-radius: 50%;
      width: 50px;
      height: 50px;
      padding: 1em;
      text-align: center;
      list-style: none;
      display: inline-block;
      line-height: 50px;
      border: 5px solid red;
      margin-right: -1em;
      z-index: 0;
      transition: width 0.5s, height 0.5s, background-color 1s, line-height 0.5s;
      
    }

    li:hover {
      display: inline-block;
      position:relative;
      width: 90px;
      height: 90px;
      z-index: 10;
      background-color: green;
      line-height: 90px;
    }
<body>
  <main>
    <h1>
      My animated Menu
    </h1>
    <div class="menu">
      <ul>
        <li>X</li>
        <li>Y</li>
        <li>Z</li>
      </ul>
    </div>
  </main>
</body>

Upvotes: 1

Views: 264

Answers (1)

GuCier
GuCier

Reputation: 7405

Use CSS3 transforms, this way the element can freely move or scale into the DOM without affecting the layout size.

A nice bonus: the animation will be more efficient in terms of fps as the layout won't be re-computed on each frame (an the GPU will be used)

ul {
  padding-top: 50px;
}

li {
  background-color: purple;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  padding: 1em;
  text-align: center;
  list-style: none;
  display: inline-block;
  line-height: 50px;
  border: 5px solid red;
  margin-right: -1em;
  z-index: 0;
  transition: transform 0.5s, background-color 1s;
}

li:hover {
  display: inline-block;
  position: relative;
  transform: scale(1.5);
  z-index: 10;
  background-color: green;
}
<div class="menu">
  <ul>
    <li>X</li>
    <li>Y</li>
    <li>Z</li>
  </ul>
</div>

Upvotes: 1

Related Questions