YTRdev
YTRdev

Reputation: 41

Flexbox 4 Item Layout

I am having trouble getting flex to work with my current layout. I am trying to get the vertical space between 1 and 3 to go away. I realize I could solve this by wrapping these two in a container, but I would prefer not to do that, because I am going to use the order property of flex to move box 2 between box 1 and 3 based on a media query. I have tried using align-self: flex-start on box 1 but this doesn't seem to solve the problem. Any ideas?

.flex-con {
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  height: 300px;
}
.box {
  width: 40%;
  margin: 0 10px;
  font-size: 20px;
  text-align: center;
}

.one {
  height: 40%;
  border: 2px solid red;
}

.two {
  height: 60%;
  border: 2px solid blue;
}
.three {
  height: 50%;
  border: 2px solid green;
}
.four {
  height: 50%;
  border: 2px solid yellow;
}
<div class="flex-con">
  <div class="box one">1</div>
  <div class="box two">2</div>
  <div class="box three">3</div>
  <div class="box four">4</div>
</div>

Upvotes: 0

Views: 82

Answers (2)

vkjgr
vkjgr

Reputation: 4448

Maybe it's not the right answer, but you can have masonry style with flex-direction: column;

* {
  box-sizing: border-box;
}

.flex-con {
  display: flex;
  flex-wrap: wrap;
  flex-direction: column;
  height: 300px;
}

.box {
  font-size: 20px;
  text-align: center;
}

.one {
  flex: 0 0 40%;
  border: 2px solid red;
}

.two {
  flex: 0 0 60%;
  border: 2px solid blue;
}
.three {
  flex: 0 0 50%;
  border: 2px solid green;
}
.four {
  flex: 0 0 50%;
  border: 2px solid yellow;
}
<div class="flex-con">
  <div class="box one">1</div>
  <div class="box two">2</div>
  <div class="box three">3</div>
  <div class="box four">4</div>
</div>

Upvotes: 1

Adam Karacsony
Adam Karacsony

Reputation: 161

If you're willing to give up the current order of your items, then you can use flex-direction: column; as seen here. Otherwise, you can achieve the exact layout described using JavaScript.

Upvotes: 0

Related Questions