Search code examples
csshoverbackground-color

CSS: Color fades in on hover but I cant get it to fade away when the mouse moves away


I am building a portfolio site and I want each project's div to have a color change on hover. I've coded it so the background color and text slowly changes when the mouse hovers over the div. However, when the mouse moves away it abruptly changes color back. I would like it to fade back to the original color slowly (rather than abruptly), using CSS if possible.

HTML:

    <div class="hacker col-xl-6 col-md-6 mb-4">
        <a href="http://text.com/filler/">
      <div class="card card-body border-0 shadow">
        <img src="img/filler.png" class="card-img-top" alt="Filler">
        <div class="card-body text-center">
          <h5 class="title1 mb-0">Filler</h5>
          <div class="subtitle ">Web Design</div>
        </div>
      </div>
    </a>
    </div>

CSS:

    .card:hover{
        background-color: #12455a;
        color: ##fff;
        -webkit-transition: background-color .3s;
        transition: background-color .3s; 
    }

    .card:hover .title1 {
        color: #fff !important;
    -webkit-transition: background-color .3s;
    transition: background-color .3s; }

.card:hover .subtitle {
    color: #fff !important;
    -webkit-transition: background-color .3s;
    transition: background-color .3s;
}

I expect that when the mouse moves away from the element, the colors will fade back to their original state with the same transition timing as when they fade in, but currently the color changes back abruptly.


Solution

  • You want to apply the transition to .card directly, not the :hover:

    .card {
      -webkit-transition: background-color .3s;
      transition: background-color .3s;
    }
    
    .card:hover {
      background-color: #12455a;
      color: #fff;
    }
    <div class="hacker col-xl-6 col-md-6 mb-4">
      <a href="http://text.com/filler/">
        <div class="card card-body border-0 shadow">
          <img src="img/filler.png" class="card-img-top" alt="Filler">
          <div class="card-body text-center">
            <h5 class="title1 mb-0">Filler</h5>
            <div class="subtitle ">Web Design</div>
          </div>
        </div>
      </a>
    </div>

    Also note that you only need to apply it to .card itself, and not the child elements.

    As an aside, you don't need to set your color on the child elements, as it will cascade down from the parent .card:hover (though you have a syntax error preventing this from happening in your above code -- I've fixed this up in my example).