CSS transition ignores width

后端 未结 1 597
温柔的废话
温柔的废话 2021-01-17 20:15

I have an tag which is displayed as a block. On page load, its width is increased by a css animation from zero to some percentage of the containing div (th

相关标签:
1条回答
  • 2021-01-17 20:41

    When you set width using animation you will override any other width defined with CSS inluding the one defined by hover. The styles inside a keyframes is more specific than any other styles:

    CSS Animations affect computed property values. This effect happens by adding a specified value to the CSS cascade ([CSS3CASCADE]) (at the level for CSS Animations) that will produce the correct computed value for the current state of the animation. As defined in [CSS3CASCADE], animations override all normal rules, but are overridden by !important rules. ref

    A workaround is to consider both width/max-width properties to avoid this confusion:

    .home-bar {
      text-decoration: none;
      background-color: white;
      color: #5e0734;
      display: block;
      animation: grow0 1.5s forwards;
      transition: color, background-color, max-width 0.2s linear;
      border: 2px solid #5e0734;
      max-width: 75%; /*Set max-wdith*/
    }
    
    .home-bar:hover {
      background-color: #5e0734;
      color: white;
      max-width: 100%; /* Update the max-width of hover*/
      text-decoration: none;
    }
    
    /*Animate width to 100%*/
    @keyframes grow0 {
      from {
        width: 10%;
      }
      to {
        width: 100%;
      }
    }
    <a href="#" id="bar0" class="home-bar">LINK</a>

    0 讨论(0)
提交回复
热议问题