html - 制作背景图像以适应 flex 容器

标签 html css flexbox background-image

我使用 flexbox 创建了一个网格,它允许 3 个图像并排对齐。我给它们设置了 33.333% 的宽度,因此它们完全适合。

但是现在我想介绍一个 css 悬停效果,当您将鼠标悬停在图像上时,另一个图像会淡入。

我的效果很好,但我遇到的问题是悬停时淡入的图像太大,因此只有大约 75% 的图像出现在容器中。

我得到淡入淡出效果的代码here ,但尽管我一直在操纵代码,但我无法让图像完全 100% 适合容器。两张图片的尺寸完全相同。

.container {
  display: flex;
  flex-wrap: wrap;
}

.box {
  flex: 1
}

.bord {
  padding: 0;
  margin: 0;
  -webkit-box-sizing: border-box;
}

.crossfd {
  background: url("https://picsum.photos/200/200?image=0");
  display: inline-block;
  background-size: cover;
}

.crossfd img {
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.crossfd img:hover {
  opacity: 0;
}
<div class="container">
  <div class="box bord crossfd">
    <img src="https://picsum.photos/200/300?image=1" width="100%" alt="Lou" />
  </div>
  <div class="box bord crossfd">
    <img src="https://picsum.photos/200/300?image=2" width="100%" alt="Lou" />
  </div>
  <div class="box bord crossfd">
    <img src="https://picsum.photos/200/300?image=3" width="100%" alt="Lou" />
  </div>
</div>

最佳答案

尝试在 .crossfd 类上添加 background-size: cover;

您也可以尝试contain100%,阅读 MDN 上的规范.

The background-size CSS property specifies the size of the background images. The size of the image can be fully constrained or only partially in order to preserve its intrinsic ratio.

关于html - 制作背景图像以适应 flex 容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38295001/

相关文章:

html - 为什么我的页脚中的图像没有留在容器内?

html - textarea 根据里面的内容调整大小

html - Safari/Chrome flex-parent 100% height + padding 和 100% height child

html - DT 和 DD 的 CSS 等高

html - Bootstrap 和 html 中的表单问题

jquery - 将鼠标悬停在包含 div 上并不总是有效

css - 3 个 span 排成一排,每个 buy 宽度不同

javascript - 点击打印页面后,CSS 与实际页面不同

javascript - 防止 flex 元素中的文本区域和镜像内容随内容动态扩展

html - 如何在 <hr> 中间插入按钮