有没有办法使用CSS获得图像的外层?

时间:2017-07-19 03:00:38

标签: html css

更新

我不知道为什么我被投票,如果有人能告诉我我做错了会很酷,如果你确定你的答案我可以接受或是作为答案和如何做到这一点的简单想法。



.gallery {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  text-align: center;
}

.gallery img {
  min-width: 33%;
  max-width: 33%;
  min-height: 120px;
  max-height: 120px;
}

<div class="gallery">
  <!--Images users provide examples:-->
  <img src="https://unsplash.it/200">
  <img src="https://unsplash.it/200/100">
  <img src="https://unsplash.it/100/300">
  <!--etc...-->
</div>
&#13;
&#13;
&#13;

没关系,但我注意到有些图像看起来很丑,因为它们是水平图像或垂直图像,我给它们一个方形的形状(当我给它们时,我不喜欢它们看起来的样子宽度/高度自动,因为它们一起看起来混乱和坏。)

我最近做的是在网络的另一部分是做类似的事情:

&#13;
&#13;
.image-cool {
  min-width: 230px;
  max-width: 230px;
  min-height: 280px;
  max-height: 280px;
  /*Has a rectangle shape*/
  background: #eee;
}

.image-cool img {
  max-width: 230px;
  max-height: 230px;
}
&#13;
<div class="image-cool">
  <img src="https://unsplash.it/200">
</div>
&#13;
&#13;
&#13;

最后一段代码的工作原理如下:

如果您将多个带有图像的div放在屏幕中,那么图像将会调整其宽度和高度受到容器的限制,图像看起来不再糟糕。

这里的问题是,如果我可以使用CSS在第一个代码中获得第二个代码的相同结果,而不添加像div或容器那样的更多HTML。

为什么我不想要另一个div? 因为第一部分的当前HTML对于某些长脚本来说是必不可少的,是的,我可以修改它,但这需要时间,我只是想看看我是否可以节省一些时间。

非常感谢你的时间! :)

1 个答案:

答案 0 :(得分:1)

您可以在img上使用background-imagebackground-size: cover,而不是使用div代码,因此任何图片大小都可以放入元素中。

&#13;
&#13;
.gallery {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  text-align: center;
}

.gallery-image {
  width: 33%;
  height: 120px;
  background-repeat: no-repeat;
  background-position: center center;
  background-size: cover;
}
&#13;
<div class="gallery">
  <div class="gallery-image" style="background-image:url(https://unsplash.it/100/300)"></div>
  <div class="gallery-image" style="background-image:url(https://unsplash.it/200/100)"></div>
  <div class="gallery-image" style="background-image:url(https://unsplash.it/200)"></div>
</div>
&#13;
&#13;
&#13;