Benjie Songsong
Benjie Songsong

Reputation: 3

CSS float help needed for 3 boxes to stack correctly

I'm having trouble using float to create a specific layout. The problem are three boxes/containers that need are in order to have the first box and the third box be on the same line, while the second box is set underneath them. I can only seem to have the second box float right to third box. However I want the third box to float right, while the first box floats left. If you see the code in code pen, my goal is to have the green box in line with red box and the blue box below them. Thanks!

https://codepen.io/benjiesongsong/pen/VwZpRGN

.container {
  width: 1200px;
  overflow: auto;
  margin: 0 auto
}

.box1 {
  width: 800px;
  height: 400px;
  background: red;
  float: left;
}

.box2 {
  width: 800px;
  height: 400px;
  background: blue;
  float: left;
}

.box3 {
  width: 400px;
  height: 400px;
  background: green;
  float: right;
}
<div class="container">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
</div>

Upvotes: 0

Views: 171

Answers (1)

Johannes
Johannes

Reputation: 67748

As long as you use floats, the order settings in your codepen have no effect (they would only apply to flexbox children) - you have to change the order of elements in the HTML code.

.container {
  width: 1200px;
  overflow: auto;
  margin: 0 auto
}

.box1 {
  width: 800px;
  height: 400px;
  background: red;
  float: left;
}

.box2 {
  width: 800px;
  height: 400px;
  background: blue;
  float: left;
}

.box3 {
  width: 400px;
  height: 400px;
  background: green;
  float: right;
}
<div class="container">
  <div class="box1"></div>
  <div class="box3"></div>
  <div class="box2"></div>
</div>

But if you use flexbox, you can do it with the order you have in your HTML, using display: flex and flex-wrap for the container and order settings for the children elements:

.container {
  width: 1200px;
  overflow: auto;
  margin: 0 auto;
  display: flex;
  flex-wrap: wrap
}

.box1 {
  width: 800px;
  height: 400px;
  background: red;
  order: 1;
}

.box2 {
  width: 800px;
  height: 400px;
  background: blue;
  order: 3;
}

.box3 {
  width: 400px;
  height: 400px;
  background: green;
  order: 2;
}
<div class="container">
  <div class="box1"></div>
  <div class="box2"></div>
  <div class="box3"></div>
</div>

Upvotes: 1

Related Questions