【问题标题】:kinda stuck in using scale() property while hovering image悬停图像时有点卡在使用 scale() 属性
【发布时间】:2021-09-10 00:56:35
【问题描述】:

我有这张图片,它在 class="image-wrapper" 的 div 内。我要做的就是:

  1. 在将鼠标悬停在图片上时显示.image-wrapper::before,使其类似于图片标题
  2. 还在 img 上使用 transform: scale(1.1),这样它在悬停时增长很小

我的问题描述

为了在图片中显示标题(第 1 部分),使用 ::before,我们不能直接在 img 上使用它,因为它们是替换元素,所以我将 imgdivclass="image-wrapper" 括起来在div 上使用::before。它像我预期的那样工作得很好。现在对于第二部分,我无法同时渲染两个属性。我有点困惑。

.image-wrapper {
  border: 2px solid black;
  display: inline-block;
  overflow: hidden;
}

.image-wrapper::before {
  content: 'Hello';
  height: auto;
  width: auto;
  padding: 4px;
  margin-left: 8px;
  background: rgba(0, 0, 240, 0.3);
  color: white;
  font-size: 20px;
  position: absolute;
  opacity: 0;
}

img {
  width: 100%;
}

img:hover {
  transform: scale(1.1);
  transition: all 0.2s;
  cursor: pointer;
}


/*HERE IS THE PROBLEM*/

.image-wrapper:hover::before {
  opacity: 1;
}
<div class="image-wrapper">
  <img src="https://images.unsplash.com/photo-1624215824600-ed3118b76873?ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDMwfDZzTVZqVExTa2VRfHxlbnwwfHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60">
</div>

【问题讨论】:

    标签: html css image hover


    【解决方案1】:

    在你的代码中有点像,但是 before 伪元素不会显示在它的元素之上,除非你给它一个更高的z-index

    此外,这个 sn-p 稍微改变了 CSS,因此它正在寻找的是悬停在 image-wrapper 类上,用于 Hello 和 img 缩放。

    .image-wrapper {
      display: inline-block;
      overflow: hidden;
    }
    
    .image-wrapper::before {
      content: 'Hello';
      height: auto;
      width: auto;
      padding: 4px;
      background: pink margin-left: 8px;
      background: rgba(0, 0, 240, 0.3);
      color: white;
      font-size: 20px;
      position: absolute;
      opacity: 0;
    }
    
    img {
      width: 100%;
    }
    
    .image-wrapper:hover img {
      transform: scale(1.1);
      transition: all 0.2s;
      cursor: pointer;
    }
    
    .image-wrapper:hover::before {
      opacity: 1;
      z-index: 100;
    }
    <div class="image-wrapper">
      <img src="https://images.unsplash.com/photo-1624215824600-ed3118b76873?ixid=MnwxMjA3fDB8MHx0b3BpYy1mZWVkfDMwfDZzTVZqVExTa2VRfHxlbnwwfHx8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60">
    </div>

    【讨论】:

    • @A Haworth 谢谢。我已经编辑了在.image-wrapper 类上添加border: 2px solid black; 的代码,并且在添加边框之后为什么图像底部会出现丑陋的填充。这个边框完美地覆盖在显示一些填充的底部之外的每一侧。也请检查那个
    • 这是一个不同的问题。
    猜你喜欢
    • 2021-09-11
    • 1970-01-01
    • 2022-08-23
    • 2013-03-17
    • 1970-01-01
    • 2021-11-06
    • 2013-06-24
    • 2017-12-13
    • 2015-06-08
    相关资源
    最近更新 更多