居中替换间隙

时间:2018-07-13 07:53:33

标签: css

我有一个div,它会根据窗口大小进行扩展和收缩,这会将图像折叠成我喜欢的不同行,但是如何防止div中屏幕右侧的间隙是由于图像没有足够的空间来容纳?

如果图像没有足够的空间容纳上一行,那么我基本上想将图像水平排列在行的中央,这也会减小div宽度。

这是我视觉上的意思

目前的行为 enter image description here

这就是我想要的行为,这是照相馆的照片 enter image description here

并且我仍然想保留如何将div调整大小或将其扩展到特定大小时图像将减少的行数,有时会导致图像行数变长。

enter image description here

这是代码

#container{
  background-color: gray;
  width: 40%;
}

img{
  width: 150px;
}
<div id='container'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
</div><!--</container>-->

1 个答案:

答案 0 :(得分:3)

您可以使用CSS网格布局实现类似的行为:

#container{
  background-color: gray;
  width: 60%;
  margin: auto;
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
  grid-gap: .25em;
}

img{
  width: 100%;
}
<div id='container'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
  <img src='http://www.wallpapereast.com/static/images/MTM3NjEyNzY4MzgyNTU5NDc0.jpg'>
</div><!--</container>-->