CSS:链接悬停时的背景动画

xdyibdwo  于 2023-03-25  发布在  其他
关注(0)|答案(2)|浏览(133)

我想给我的链接添加一个悬停效果,就像这样:https://codyhouse.co/ds/components/app/related-articles
我使用以下CSS代码:

a.headline h3:hover {
    background-size: 100% 100%;
}
a.headline h3 {
    color: $body-color;
    background-repeat: no-repeat;
    background-image: linear-gradient(transparent 50%, rgb(228, 227, 255));
    background-size: 0% 100%;
    will-change: background-size;
    transition: background-size 0.3s ease-in-out;
}

不幸的是,结果与示例中的不一样。是有某种JS代码还是我的CSS中有错误?
下面是一个工作演示:https://codepen.io/cray_code/pen/poOQJjX

mefy6pfw

mefy6pfw1#

在这个例子中,它是相反的。a嵌套在h3中。这是因为默认情况下a是内联的。你可以通过将h3设置为display: inline;来解决这个问题。

a.headline {
  max-width: 200px;
  display: block;
  color: #000;
  text-decoration: none;
  line-height: 1.5;
  font-family: Arial;
  margin: 2rem auto;
}

a.headline h3:hover {
  background-size: 100% 100%;
}

a.headline h3 {
  display: inline;
  color: $body-color;
  background-repeat: no-repeat;
  background-image: linear-gradient(transparent 50%, rgb(228, 227, 255));
  background-size: 0% 100%;
  will-change: background-size;
  transition: background-size 0.3s ease-in-out;
}
<a href="#" class="headline">
  <h3>Lorem ipsum dolor sit amet, consectetuer adipiscing elit </h3>
</a>
n9vozmp4

n9vozmp42#

试试这个:

a.headline {
    color: var(--color-contrast-higher);
    text-decoration: underline;
    background-repeat: no-repeat;
    background-image: linear-gradient(transparent 50%,hsla(250,84%,54%,0.2) 50%);
    background-size: 0% 100%;
    will-change: background-size;
    transition: background-size .3s ease-in-out;
}

a.headline:hover {
    background-size: 100% 100%;
}
<h3>
    <a href="#" class="headline">
    Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
    </a>
</h3>

相关问题