css 悬停在图像内时应用图像覆盖

9njqaruj  于 2023-01-06  发布在  其他
关注(0)|答案(1)|浏览(123)

我有两个flexbox列。左列包含文本;右栏包含图片。这两栏应分别占页面宽度的60%和40%。文字的尺子大于图片的高度。我希望图片上有半透明的覆盖层;当我悬停在覆盖层上时,我希望覆盖层消失。
但是,我无法显示覆盖,而且似乎无法将悬停区域限制为图片大小--右列中的任何地方,什至图片下方,都会触发悬停效果。
因为我希望页面能够响应,所以我不想手动设置图片大小(或aspect-ratio):它应该填充右列的宽度,右列应该填充页面宽度的40%--这里不要用px
这里有一个我正在尝试做的事情的快速模型。在这个例子中,黄色的#img-container在图像底部以下展开,绿色的.overlay没有显示。两者都应该与图像的大小完全相同。
Fiddle here.
我的方法对吗?有没有什么明显的我遗漏了的东西?我对网页设计还是个新手...谢谢你的帮助!

3qpi33ja

3qpi33ja1#

要能够在特定元素上放置“覆盖”:

  • 你需要你覆盖的元素(你的#container-img)是position: relative
  • overlay 本身必须相对于position: absolute元素定位。
  • 根据您的需要,通过给toprightbottom和/或left赋值,或者像我在代码片段中使用的那样,定义它们的简写inset属性,将 overlay 定位在元素内部。当您想要 overlay 图像时,inset: 0会将 overlay 拉伸到其父#container-img的所有边。
  • 剩下要做的就是定义悬停#container-img时的CSS。

我在代码片段中注解了我的更改和添加:

#container {
  display: flex;
  gap: 50px;
}

#container-text {
  flex: 3;
}

#container-img {
  flex: 2;
  background-color: yellow;
  align-self: flex-start;
}

/*************************/
/* Changes and additions */
/*************************/
/* Changed */
#container-img img {
  display: block; /* removes small whiete space below image */
  /* disable this property to see the difference! */

  width: 100%;
  opacity: 20%;
}

#container-img .overlay {
    content: "";
    position: absolute;
    inset: 0; /* shorthand for T/R/B/L properties */
    background: rgb(0,255,0,.2); /* a semi transparent color */
}

/* ADDED */
#container-img {
  position: relative; /* new stacking context to position overlay */
}
#container-img:hover .overlay {
  display: none; /* hide the overlay on hover */
}
<div id="container">

  <div id="container-text">
    <p>teeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeext</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
    <p>text</p>
  </div>

  <div id="container-img">
    <img src="https://play-lh.googleusercontent.com/IeNJWoKYx1waOhfWF6TiuSiWBLfqLb18lmZYXSgsH1fvb8v1IYiZr5aYWe0Gxu-pVZX3" alt="profile picture">
    <div class="overlay"></div>
  </div>

</div>

相关问题