过渡效果不适用于线性渐变到底部的悬停

时间:2020-09-20 14:46:52

标签: css css-transitions linear-gradients

我有两个框,每个框都有:hover选择器,它们可以转换线性渐变背景图像。 线性渐变到顶部在过渡时效果很好(下面的代码)。

.box7:hover{
            color: #FFF; 
            background-image: linear-gradient(to top, #000 50%, #fff 50%);
            background-position: 0% 100%;
            background-size: 100% 200%;
            transition: all 1s ease;
            border: none;
        }

但是我在到底部的线性渐变方面遇到了问题,过渡效果似乎不起作用(下面的代码)。

.box2:hover{
            color: #FFF; 
            background-image: linear-gradient(to bottom, #000 50%, #fff 50%);
            background-position: 100% 0%;
            background-size: 100% 200%;
            transition: all 1s ease;
            border: none;
        }

任何帮助将不胜感激。 以下是检查链接(将鼠标悬停在所有框上) https://conrad93.github.io/linear-gradient-sliding-effect/boxbox.html

1 个答案:

答案 0 :(得分:0)

问题在于,当您将鼠标悬停在元素上时,您的样式不会被应用。因此,解决方案是将这些样式也应用于元素的默认状态。像这样:

// html

<div class="container">
  <div class="box box-1"></div>
  <div class="box box-2"></div>
  <div class="box box-3"></div>
  <div class="box box-4"></div>
</div>

//  CSS

.container {
  display: flex;
}

.box {
  width: 100px;
  height: 100px;
  border: solid 1px red;
  margin: 5px;
  transition: all .4s ease;
  background-color: lightgoldenrodyellow;
}

.box-1 {
  background-image: linear-gradient(to top, crimson 50%, lightgoldenrodyellow 50%);
  background-position: 0% 0%;
  background-size: 100% 200%;
}

.box-1:hover {
  background-position: 0% 100%;
}

.box-2 {
  background-image: linear-gradient(to bottom, crimson 50%, lightgoldenrodyellow 50%);
  background-position: 0% -100%;
  background-size: 100% 200%;
}

.box-2:hover {
  background-position: 0% -200%;
}

.box-3 {
  background-color: crimson;
  background-image: linear-gradient(to bottom left, crimson 50%, lightgoldenrodyellow 50%);
  background-position: 0% 100%;
  background-size: 200% 200%;
  background-repeat: no-repeat;
}

.box-3:hover {
  background-position: 0% -100%;
}

.box-4 {
  background-image: linear-gradient(to top right, crimson 50%, lightgoldenrodyellow 50%);
  background-position: 0% -100%;
  background-size: 200% 200%;
  background-repeat: no-repeat;
}

.box-4:hover {
  background-position: 0% 100%;
}

在悬停状态的声明块中,只需声明正在更改的那些属性,在这种情况下为background-position

这是JsFiddle上的一个有效示例。

您可能还希望对角渐变从元素的左下角向上进行动画处理。这样做有些棘手,但是您可以在示例中看到它的运行。要了解它为什么起作用,您需要了解background-position属性中x和y的含义。 MDN docs是学习的好地方。