用不同尺寸的物品包装的弹性盒

时间:2019-02-26 19:41:07

标签: html css css3 flexbox

我可以使用具有以下文档结构的flexbox实现这种布局吗?

Layout

我想要左边的大<img>,右边有两个较小的图像并包装。

这就是我所做的,在display: flexgallery-container上分别放置了flex-wrap

.container {
  height: 100%;
}

.container .gallery-container {
  background-color: #f6f6f6;
  display: flex;
  flex-wrap: wrap;
  width: 300px;
  align-items: flex-start;
}

.container .gallery-container .gallery-big-image {
  display: block;
  width: 200px;
  height: 200px;
  background: lavender;
}

.container .gallery-container .gallery-small-img {
  display: block;
  width: 100px;
  height: 100px;
  background-color: purple;
}
<div class="container">
  <div class="gallery-container">
    <div class="gallery-big-image">big</div>
    <div class="gallery-small-img">small</div>
    <div class="gallery-small-img">small</div>
    <div class="gallery-small-img">small</div>
    <div class="gallery-small-img">small</div>
    <div class="gallery-small-img">small</div>
  </div>
</div>

codepen

2 个答案:

答案 0 :(得分:1)

flexbox的布局笨拙且效率低下,原因如下:CSS-only masonry layout

但是,使用CSS Grid,布局相对简单易行。

未更改HTML。

.gallery-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, 100px);
  grid-auto-rows: 100px;
  width: 300px;
  background-color: #f6f6f6;
}

.gallery-big-image {
  grid-column: span 2;
  grid-row: span 2;
  background: lavender;
}

.gallery-small-img {
  background-color: purple;
  color: white;
}
<div class="container">
  <div class="gallery-container">
    <div class="gallery-big-image">big</div>
    <div class="gallery-small-img">small 1</div>
    <div class="gallery-small-img">small 2</div>
    <div class="gallery-small-img">small 3</div>
    <div class="gallery-small-img">small 4</div>
    <div class="gallery-small-img">small 5</div>
    <div class="gallery-small-img">small 6 (continues wrapping)</div>    
    <div class="gallery-small-img">small 7 (continues wrapping)</div>        
  </div>
</div>

答案 1 :(得分:0)

如何改用grid layout

.container {
  height: 100%;
}

.gallery-container {
  background-color: #f6f6f6;
  width: 300px;
  height: 100px;
  display: grid;
  grid-template-rows: repeat(3, 1fr);
  grid-template-columns: repeat(3, 1fr);
}

.gallery-img {
  background: purple;
  width: 100px;
  height: 100px;
}

.gallery-img-large {
  background: lavender;
  width: 200px;
  height: 200px;
  grid-column-start: 0;
  grid-column-end: span 2;
  grid-row-start: 0;
  grid-row-end: span 2;
}
<div class="container">
  <div class="gallery-container">
    <div class="gallery-img-large">big</div>
    <div class="gallery-img">small</div>
    <div class="gallery-img">small</div>
    <div class="gallery-img">small</div>
    <div class="gallery-img">small</div>
    <div class="gallery-img">small</div>
  </div>
</div>