How do I create a transition between 2 different font awesome icons?

Advertisements

I have this button in HTML:

<button id="sidebar-toggle-button" class="btn btn-primary header-btn" type="button" data-bs-toggle="offcanvas"
      data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
      <div class="icons">
        <i id="sidebar-toggle-default" class="fa-solid fa-bars sidebar-toggle-icon-default"></i>
        <i id="sidebar-toggle-active" class="fa-solid fa-bars-staggered sidebar-toggle-icon-active"></i>
      </div>
    </button>

It’s part of a collapsible sidebar that I made with Bootstrap (officially called an offcanvas). When I hover my mouse over this, I want the "sidebar-toggle-default" icon to transition to the "sidebar-toggle-active"icon.

I found this thread that tells me it’s possible to do this with just CSS, but the effect is too complicated for what I’m trying to do, and I can’t seem to replicate it in my own code either.

I want a very simple animation. The default icon is 3 bars stacked vertically, and the "active" icon below it is the same but the middle bar has a slight offset relative to the rest. When I hover over the icons, I want the transition to look like the middle bar is pushed forward. Is there a way to accomplish this?

>Solution :

This is quite an easy trick – put the second icon as position: absolute:

.icons {
  position: relative;
  display: flex;
  i {
    transition: opacity .4s;
    &:last-child {
      position: absolute;
      left: 0;
      top: 0;
      opacity: 0;
    }
  }
}

.header-btn {
  &:hover {
    .icons {
      i {
        &:first-child {
          opacity: 0;
        }
        &:last-child {
          opacity: 1;
        }
      }
    }
  }
}
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.2/css/all.min.css" rel="stylesheet"/>

<button id="sidebar-toggle-button" class="btn btn-primary header-btn" type="button" data-bs-toggle="offcanvas"
  data-bs-target="#offcanvasExample" aria-controls="offcanvasExample">
  <div class="icons">
    <i id="sidebar-toggle-default" class="fa-solid fa-bars sidebar-toggle-icon-default"></i>
    <i id="sidebar-toggle-active" class="fa-solid fa-bars-staggered sidebar-toggle-icon-active"></i>
  </div>
</button>

Leave a ReplyCancel reply