CSS display none and opacity animation with keyframes not working

前端 未结 8 2033
广开言路
广开言路 2020-12-01 10:43

I have a very basic piece of HTML with the objective of animating from display: none; to display: block with opacity changing from 0 to 1.

8条回答
  •  栀梦
    栀梦 (楼主)
    2020-12-01 11:33

    If you are using @keyframes you should use -webkit-animation instead of -webkit-transition. Here is the doc for @keyframes animation: https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations.

    See code snippet below:

    .parent {
      background-color: #000;
      color: #fff;
      width: 500px;
      height: 500px;
      padding: 5px;
    }
    .myDiv {
      display: none;
      opacity: 0;
      padding: 5px;
      color: #600;
      background-color: #cec;
    }
    .parent:hover .myDiv {
      display: block;
      opacity: 1;
      /* "both" tells the browser to use the above opacity
      at the end of the animation (best practice) */
      -webkit-animation: display-none-transition 1s both;
      animation: display-none-transition 1s both;
    }
    @-webkit-keyframes display-none-transition {
      0% {
        opacity: 0;
      }
    }
    @keyframes display-none-transition {
      0% {
        opacity: 0;
      }
    }
    Hover on me...
    Hello!


    2016 UPDATED ANSWER

    To reflect today's best practices, I would use a transition instead of an animation. Here is the updated code:

    .parent {
      background-color: #000;
      color: #fff;
      width: 500px;
      height: 500px;
      padding: 5px;
    }
    .myDiv {
      opacity: 0;
      padding: 5px;
      color: #600;
      background-color: #cec;
      -webkit-transition: opacity 1s;
      transition: opacity 1s;
    }
    .parent:hover .myDiv {
      opacity: 1;
    }
    Hover on me...
    Hello!

提交回复
热议问题