使用Flexbox的自适应正当图片库

时间:2018-10-23 08:42:31

标签: css flexbox gallery

基于此示例,我正在尝试制作图片库:

body { margin: 0; background: #333; }
header { 
  padding: .5vw;
  font-size: 0;
  display: -ms-flexbox;
  -ms-flex-wrap: wrap;
  -ms-flex-direction: column;
  -webkit-flex-flow: row wrap; 
  flex-flow: row wrap; 
  display: -webkit-box;
  display: flex;
}
header div { 
  -webkit-box-flex: auto;
  -ms-flex: auto;
  flex: auto; 
  width: 200px; 
  margin: .5vw; 
}
header div img { 
  width: 100%; 
  height: auto; 
}
@media screen and (max-width: 400px) {
  header div { margin: 0; }
  header { padding: 0; }
  
}
<header>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-1.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-2.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-3.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-4.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-5.jpg" alt></div>
  <!-- images placed inside block elements to deal with a Firefox rendering bug affecting  scaled flexbox images -->
</header>

我所有的图像均为200x200px,它的工作原理像一个超级按钮,但是我需要用左对齐的相同固定原始图像大小替换最后一行。

按照其他答案的建议,我尝试添加一个::after元素来填充空白,但是我没有成功。

最终,我正在考虑使用Javascript根据媒体查询和每行图像数添加无显示的伪图像。

还有其他更好的方法可以做到这一点吗?

我的代码:

.c-gallery {
    font-size: 0;
    max-width: 1600px;
    display: flex;
    flex-flow: row wrap;
    a {
        flex: auto;
        width: 150px;
        margin: 5px 5px 0 0;
          img {
              height: auto;
          }
       }
    }

1 个答案:

答案 0 :(得分:0)

以下内容如何。它使用CSS网格。 通过玩grid-template-columns: repeat(3, 200px);,您可以更改列数。

body { margin: 0; background: #333; }
header { 
  padding: .5vw;
  font-size: 0;
  display: grid;
  grid-template-columns: repeat(3, 200px);
  grid-gap: .5vw
}

header div img { 
  width: 100%; 
  height: auto; 
}
@media screen and (max-width: 400px) {
  header div { margin: 0; }
  header { padding: 0; }
}
<header>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-1.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-2.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-3.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-4.jpg" alt></div>
<div><img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/4273/jeremiah-wilson-5.jpg" alt></div>
  <!-- images placed inside block elements to deal with a Firefox rendering bug affecting  scaled flexbox images -->
</header>