Search code examples
cssbackgroundcss-animationsmousehover

CSS gradual background change of a moving div?


What I am trying to achieve is this:

enter image description here

a coin (ring) sinking into the slot. Initially it is blue. when it enters the red background it becomes white. when it reaches the slot - it is gradually disappearing.

and this is what I have come up with so far:

  .circle {
  transition: all 1s ease;
  width: 200px;
  height: 200px;
  border-radius: 50%;
  background: url(http://a5w.org/up/uploads/mike/2017-11-15/1510773962_red_square.png) no-repeat;
  background-color: #fff;
  background-position: 0 0;
  position: absolute;
  top: 0;
  left: 20px;
  z-index: 22;
}

.circle:hover {
  margin-top: 100px;
  background-position: 0px -100px;
}

.rect {
  margin-top: 200px;
  width: 100%;
  height: 400px;
  background: #666;
  transition: all 0.5s ease;
}

.slot{

  position: absolute;
  z-index: 666;
  background: #666;
  margin-top: 50px;

  height: 200px;
  width: 230px;
  border-top: solid 2px #333


}

https://jsfiddle.net/y4fpyjsa/17/

This looks more like a hack though so I am wondering if there is a better solution, probably? Without moving backgrounds and extra layers.


Solution

  • You can use 2 circles and play with z-index. One will be a part of the rect but hidden with overflow:hidden and will only be visible on hover when you increase its margin. The second one (the main one) will be hidden on hover below the rect because its low z-index.

    With this trick you will visually have one circle with 2 different border colors and no need to change background.

    .circle {
      transition: all 1s ease;
      width: 120px;
      height: 120px;
      border-radius: 50%;
      background-color: transparent;
      border:40px solid red;
      background-position: 0 0;
      position: absolute;
      top: 0;
      left: 50%;
      margin-left:-100px;
      z-index: 22;
    }
    .white {
      top:-200px;
      border:40px solid white;
      z-index:21
    }
    
    
    body:hover .circle {
      margin-top: 100px;
    }
    
    .rect {
      margin-top: 200px;
      width: 100%;
      height: 400px;
      background: #666;
      transition: all 0.5s ease;
      position:relative;
      z-index:500;
      overflow:hidden;
    }
    
    .slot {
      position: absolute;
      z-index: 666;
      background: #666;
      margin-top: 50px;
      height: 200px;
      width: 230px;
      border-top: solid 2px #333;
      right:50%;
      margin-right:-115px;
    }
    <div class="circle">
    </div>
    <div class="slot">
    </div>
    <div class="rect">
    <div class="circle white">
    </div>
    </div>

    The only issue with this solution is that you have to make the hover effect on the container (here i used the body) as you cannot target one circle to move both of them.