Glen Padua
Glen Padua

Reputation: 507

Flexbox modify flex-item property to stack one item on top of the other

I have to achieve the below layout. Using react I am trying to create a generic gallery component using flexbox. So I'm iterating over an object containing image details like src, width and height.

enter image description here

I created this codepen - https://codepen.io/glenpadua/pen/GxdOwb?editors=1100 to try and replicate the problem.

There is an outer container of width: 1100px and a flex-container with flex-wrap: wrap.

By only adding a property to the flex-item without wrapping it with any extra divs, is it possible to stack IMG 1 and IMG 2 like the layout shown?

I don't want any extra wrapper div because I'm trying to create a generic reusable React component.

Thanks.

Upvotes: 1

Views: 412

Answers (1)

Mohamad Zeina
Mohamad Zeina

Reputation: 433

As someone has previously mentioned, you need to use CSS Grid if you'd like to get rid of the need for a wrapper div around image 1 and 2.

This is because FlexBox is technically only a 1D layout tool, so struggles with things like this where you need to change the direction of flow.

CSS grid is much better for situations where you need to vary your layout in 2D. There's a good example here: How can I use Flexbox to align two boxes in a column, next to a row?

Here's a quick example that achieves what you want without wrapping the first two boxes in their own div.

.outer {
  background: lightgrey;
  width: 1100px;
}

.inner {
  display: grid;
  flex-wrap: wrap;
}

.a {
  grid-column: 1;
  grid-row: 1 / span 1;
}

.b {
  grid-column: 1;
  grid-row: 2 / span 1;
}

.c {
  grid-column: 2;
  grid-row: 1 / span 2;
}

.d {
  grid-column: 3;
  grid-row: 1 / span 2;
}

.e {
  grid-column: 4;
  grid-row: 1 / span 2;
}
<div class='outer'>
  <div class="inner">
    <div class="a" style='width: 275px;height: 182px; background: red'>275x182</div>
    <div class="b" style='width: 275px;height: 182px; background: green'>275x182</div>
    <div class='c' style='width: 275px;height: 365px; background: purple'>275x365</div>
    <div class='d' style='width: 275px;height: 365px; background: orange'>275x365</div>
    <div class='e' style='width: 275px;height: 365px; background: papayawhip'>275x365</div>
    <div class='f' style='width: 275px;height: 400px; background: pink'>275x400</div>
    <div class='g' style='width: 275px;height: 400px; background: yellow'>275x400</div>
    <div class='h' style='width: 275px;height: 400px; background: palevioletred'>275x400</div>
  </div>
</div>

Upvotes: 2

Related Questions