css 当不透明度添加到图像时,边框消失

iyzzxitl  于 2023-05-08  发布在  其他
关注(0)|答案(3)|浏览(162)

我想在鼠标悬停时显示图像并保留边框。但是,当我添加不透明度时,边框也会消失。如何在鼠标悬停时显示图像时保持边框?“
下面是我的代码:

<div class="finishedprojects">
<img src="https://shorturl.at/bR589">
 </div>

 .finishedprojects img {
  width: 100%;
  max-width: 350px;
  height: 250px;
  object-fit: cover;
  border: solid yellow 1em;
  background-color: black;
  opacity:0;
}

.finishedprojects img:hover {
  cursor: pointer;
  opacity: 1;
}

我尝试了.finishedprojects img { border:但它不起作用。

vojdkbi0

vojdkbi01#

若要在鼠标悬停时以不透明度显示图像时保持边框可见,可以将图像包裹在另一个div内,并将边框应用于该div而不是图像

.finishedprojects .image-wrapper {
width: 100%;
max-width: 350px;
height: 250px;
object-fit: cover;
border: solid yellow 1em;
background-color: black;
position: relative;
}

.finishedprojects .image-wrapper img {
width: 100%;
height: 100%;
object-fit: cover;
opacity: 0;
position: absolute;
top: 0;
left: 0;
}

.finishedprojects .image-wrapper:hover img {
opacity: 1;
}
<div class="finishedprojects">
  <div class="image-wrapper">
    <img src="https://shorturl.at/bR589">
  </div>
</div>
9fkzdhlc

9fkzdhlc2#

您可以使用::before伪元素在图像容器上创建一个不受悬停时不透明度变化影响的边框。

.finishedprojects {
  position: relative;
  width: 100%;
  max-width: 350px;
  height: 250px;
  border: solid yellow 1em;
  background-color: black;
}

.finishedprojects img {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
  opacity: 0;
}

.finishedprojects:hover img {
  opacity: 1;
}

.finishedprojects::before {
  content: "";
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  border: solid yellow 1em;
}
afdcj2ne

afdcj2ne3#

您只需在容器类.finishedprojects中设置width: max-content;,并将边框样式移到那里。看我的片段:

.finishedprojects  {
    width: max-content;
    border: solid yellow 1em;
}

.finishedprojects img {
    width: 100%;
    max-width: 350px;
    height: 250px;
    object-fit: cover;
    background-color: black;
    opacity:0;
}

.finishedprojects img:hover {
    cursor: pointer;
    opacity: 1;
}
<div class="finishedprojects">
    <img src="https://randomuser.me/api/portraits/lego/1.jpg" alt="Demo Image">
</div>

如果您还希望在未显示图像的情况下使用黑色背景,请将背景属性background-color: black;.finishedprojects img类移动到.finishedprojects类。

相关问题