htmlcsshoverpseudo-elementmouseout

Is it possible to handle mouseout on ::after pseudo-class in CSS?


.header-section {
    width: calc(100% / 4);
    padding: 10px 15px;
    user-select: none;
    font-family: 'Nourd', sans;
    font-size: 1.2em;
    text-align: center;
    cursor: pointer;
    border-radius: 15px;
    position: relative;
}

.header-section::after {
    content: "";
    position: absolute;
    bottom: 8%;
    left: 25%;
    width: 0%;
    height: 4px;
    border-radius: 6px;
    background-image: linear-gradient(135deg, rgb(225, 60, 60), rgb(235, 126, 181));
    animation-duration: 500ms;
    animation-fill-mode: both;
    animation-name: hss-anim-out;
}

.header-section:hover::after {
    animation-name: hss-anim-over;
}

@keyframes hss-anim-over {
    from {
        width: 0%;
    }
    to {
        width: 50%;
    }
}

@keyframes hss-anim-out {
    from {
        left: 25%;
        width: 50%;
    }
    to {
        left: 75%;
        width: 0%;
    }
}
<div class="header-section header-section-selected">importer</div>
<div class="header-section">mes fichiers</div>

This my code to make my question clear. It does what I want, except it runs the animation "hss-anim-out" when the page loads. I searched how to override this, but I didn't find something which actually works. Does anyone have an idea to do this, considering it is impossible to use JavaScript for the animation because it is on the ::after pseudo-element? Thanks in advance


Solution

  • Don't use animation but transition. An idea using background properties

    .header-section {
      width: calc(100% / 4);
      padding: 10px 15px;
      user-select: none;
      font-family: 'Nourd', sans;
      font-size: 1.2em;
      text-align: center;
      cursor: pointer;
      border-radius: 15px;
      position: relative;
    }
    
    .header-section::after {
      content: "";
      position: absolute;
      bottom: 8%;
      left: 25%;
      right: 25%;
      height: 4px;
      border-radius: 6px;
      background-image: linear-gradient(135deg, rgb(225, 60, 60), rgb(235, 126, 181));
      background-size: 0% 100%;
      background-position:right;
      background-repeat: no-repeat;
      transition:background-size 0.5s, background-position 0s 0s;
    }
    
    .header-section:hover::after {
      background-size: 100% 100%;
      background-position:left;
    }
    <div class="header-section header-section-selected">importer</div>
    <div class="header-section">mes fichiers</div>