代码之家  ›  专栏  ›  技术社区  ›  Arsalan Khattak

线性渐变过渡

  •  2
  • Arsalan Khattak  · 技术社区  · 6 年前

    我想在悬停时添加线性渐变过渡。

    我做了一些研究,发现了它是如何工作的,但不幸的是,它们只适用于按钮等,而我希望它出现在图像上。

    我使用css属性添加了一个图像 背景图像 。我希望当用户悬停在图像上时,图像显示线性渐变和过渡。

    这是代码。

    .project-1 { 
        background-image: url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
        width: 350px;
        height: 250px;
        background-position: center;
        background-size: cover;
        transition: transform 0.5s , opacity 0.5s; 
    }
    
    .project-1:hover {
        
        background-image: linear-gradient(rgba(0, 0, 0, 0.39) , rgba(0, 0, 0, 0.39)) , url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
        background-position: center;
        background-size: cover;
        transform: scale(1.05);
        
    }
    <div class="project-1"></div>

    我在stackoverflow上找到的主题有按钮或简单的背景,没有任何图像。

    (我在代码中使用的图像仅用于片段)

    1 回复  |  直到 6 年前
        1
  •  3
  •   Temani Afif    6 年前

    不能使用这样的线性渐变应用淡入淡出过渡。另一种方法是在应用不透明度转换的位置使用伪元素:

    .project-1 {
      background-image: url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
      width: 350px;
      height: 250px;
      background-position: center;
      background-size: cover;
      transition: transform 0.5s, opacity 0.5s;
    }
    
    .project-1:before {
      content: "";
      position: absolute;
      top: 0;
      right: 0;
      left: 0;
      bottom: 0;
      background: rgba(0, 0, 0, 0.39);
      transition: 0.5s;
      opacity: 0;
    }
    
    .project-1:hover {
      transform: scale(1.05);
    }
    
    .project-1:hover::before {
      opacity: 1;
    }
    <div class="project-1"></div>

    或者你也可以通过背景大小或背景位置来进行另一种渐变。下面是一个例子:

    .project-1 { 
        background-image:
        linear-gradient(rgba(0, 0, 0, 0.39) , rgba(0, 0, 0, 0.39)) , url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
        width: 350px;
        height: 250px;
        background-position:0 0,center;
        background-size:100% 0%,cover;
        background-repeat:no-repeat;
        transition: 0.5s; 
    }
    
    .project-1:hover { 
        background-image: 
        linear-gradient(rgba(0, 0, 0, 0.39) , rgba(0, 0, 0, 0.39)) , url("https://cdn.pixabay.com/photo/2018/03/11/20/42/mammals-3218028_960_720.jpg");
        background-size:100% 100% ,cover;
        transform: scale(1.05);
        
    }
    <div class=“project-1”></div>