Is there a wait function in CSS?

Viewed 134

I'm trying to make a animation that makes a div element 10 pixels bigger when hovering and 10 pixels smaller when not hovering. The only problem is that when hovering, it plays the animation, and the element gets 10 pixels bigger as expected, but then the animation ends and the element returns to its original size.

This is the code currently:

.box_1 {
  background-color: white;
  border-radius: 50px;
  display: block;
  width: 300px;
  height: 400px;
  margin-left: 100px;
}

.box_1:hover {
  animation-name: bigger;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-direction: normal;
}

.box_1:not(hover) {
  animation_name: bigger;
  animation-duration: 2s;
  animation-direction: reverse;
  animation-iteration-count: 1;
}

@keyframes bigger {
  from {
    width: 300px;
    height: 400px;
  }
  to {
    width: 310px;
    height: 410px;
  }
}

I've tried playing the animation then pausing it, but I'd need a wait function. This probably can be easily solved with JavaScript, but I'm trying not to use it (because I'm lazy).

1 Answers

I'm not sure a delay is your best bet here - it sounds like what you're trying to do might be better accomplished with a transition.

Specifically, look at the CSS code for .box_2.

transition: all 1s;

There's a lot you can do with transitions, but this should get you started.

.box_2 {
  background-color: green;
  border-radius: 50px;
  width: 300px;
  height: 400px;
  transition: all 1s;
}

.box_2:hover {
  width: 320px;
  height: 420px;
}

.metabox {
  display: flex;
  justify-content: space-evenly;
}

.box {
  padding: 2em;
  margin: 2em;
}

.box_1 {
  background-color: green;
  border-radius: 50px;
  display: block;
  width: 300px;
  height: 400px;
}

.box_1:hover {
  animation-name: bigger;
  animation-duration: 2s;
  animation-iteration-count: 1;
  animation-direction: normal;
}
.box_1:not(hover) {
  animation_name: bigger;
  animation-duration: 2s;
  animation-direction: reverse;
  animation-iteration-count: 1;
}
@keyframes bigger {
  from {
    width: 300px;
    height: 400px;
  }
  to {
    width: 310px;
    height: 410px;
  }
}
<!-- example for SO question  -->
<!-- https://stackoverflow.com/questions/68594744/is-there-a-wait-function-in-css -->
<div class="metabox">
  <div class="box box_1">Box_1</div>
  <div class="box box_2">Box_2</div>
</div>

Also, depending on the context, you may not need the display: block; on .box_1, since that's the default for block-level elements.

Related