Html 制作背景图像以适合 flex 容器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38295001/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Make background image to fit in flex container
提问by markst33
I have used flexbox to create a grid which allows 3 images be aligned side by side. I have given them a width of 33.333% so they fit exactly.
我使用 flexbox 创建了一个网格,它允许 3 个图像并排对齐。我给了它们 33.333% 的宽度,因此它们完全适合。
However now I want to introduce a css hover effect where another image fades in when you hover over an image.
但是现在我想介绍一个 css 悬停效果,当您将鼠标悬停在图像上时,另一个图像会淡入。
I have the effect working fine, however the issue I am having is that the image which fades in on hover is too big and as a result only about 75% of it appears in the container.
我的效果很好,但是我遇到的问题是悬停时淡入的图像太大,因此只有大约 75% 的图像出现在容器中。
I got the code for the fade effect here, but although I have been manipulating the code I can't get the image to fit exactly 100% in the container. Both images are the exact same dimensions.
我在这里得到了淡入淡出效果的代码,但尽管我一直在操纵代码,但我无法使图像完全 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>
回答by Stickers
Try adding background-size: cover;
on .crossfd
class.
尝试添加background-size: cover;
的.crossfd
类。
You may also try contain
or 100%
, read the spec on MDN.
您也可以尝试contain
或100%
阅读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.
该
background-size
CSS属性指定的背景图像的大小。图像的大小可以完全限制或仅部分限制,以保持其固有比例。