Search code examples
htmlcsspositioncss-transitions

Vertically centering and animating icon on image hover


I have trouble vertically centering icon that drops on image hover, and I am trying to ease out its drop down. Currently it is coming down too aggressive but no matter what transition property I set (ease, ease-out etc.) it doesn't change.

https://jsfiddle.net/4br7sj0q/2/

<div class="fader">
    <a href="#">
      <img width="200" height="350" src="http://placehold.it/200x350"> 
      <span class="fa fa-search fa-3x"></span>
    </a>
</div>




.fader {
    position: relative;
    span.fa {
        position: absolute;
        top: -9999px;

        // center horizontal
        margin-left: auto;
        margin-right: auto;
        left: 0;
        right: 0;

        transition: all 0.3s ease-out;
    }
    &:hover .fa {
        top: 50%;
    }
}

Solution

  • Couple of things.

    The icon is coming a long way. You really don't need to send it 9999px away, just enough to be offscreen (or apply overflow hidden to the parent and then it can just be 1em off the top).

    Then change the transition to something like transition: all 0.5s ease;...if it's too fast, make the time longer.

    The easing function should just be ease...not ease-out...it looks more natural.

    Finally, to adjust the centering you need to drag it back up half it's own height

      transform:translateY(-50%);
    

    li {
      list-style: none;
      text-align: center;
    }
    .fader {
      position: relative;
      overflow: hidden;
      display: inline-block;
    }
    .fader img {
      -webkit-transition: all 0.3s;
      transition: all 0.3s;
      display: block;
    }
    .fader img:hover {
      opacity: 0.5;
    }
    .fader span.fa {
      color: #333;
      position: absolute;
      top: -1em;
      margin-left: auto;
      margin-right: auto;
      left: 0;
      right: 0;
      -webkit-transition: all .5s ease;
      transition: all .5s ease;
      -webkit-transform: translateY(-50%);
      transform: translateY(-50%);
    }
    .fader:hover .fa {
      top: 50%;
    }
    <link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />
    <li>
      <div class="fader">
    
        <a href="#">
          <img width="200" height="350" src="http://placehold.it/200x350"> <span class="fa fa-search fa-3x"></span>
        </a>
      </div>
    
    </li>