Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In a flexbox grid, how do I prevent the first row from pushing down the second? [duplicate]

Tags:

html

css

flexbox

I have a flex design that looks kinda like this:

.columns {
  flex-wrap: wrap;
  display: flex;
}

.column {
  display: block;
}

.column.is-8 {
   flex: none;
   width: 66.66667%;
}

.column.is-4 {
    flex: none;
    width: 33.33333%;
}

.box-1 {
  background-color: red;
  height: 200px;
}
.box-2 {
  background-color: yellow;
    height: 400px;
}
.box-3 {
  background-color: blue;
    height: 800px;
}

*, *::before, *::after {
    box-sizing: inherit;
}
<div class="columns">
  <div class="column is-8 box-1">
      Box 1
  </div>
  <div class="column is-4 box-2">
      Box 2
  </div>
  <div class="column is-8 box-3">
      Box 3
  </div>
</div>
<!-- on desktop: box 1, 2 and 3 -->
<!-- on mobile: box 1, 2 and 3 -->

How can I prevent box 2 from pushing down box 3? So it would look like this:

enter image description here

Update

I would like to add that on mobile, the boxes should be in the same order (e.g. 1, 2 then 3)

like image 691
FooBar Avatar asked Jan 25 '23 15:01

FooBar


2 Answers

You need to setup your template a bit differently as box 1 and 3 is in the same column. You can achieve the desired layout by wrapping box 1 and 3 in a div.

.columns {
  display: flex;
  width: 100%;
}

.column {
  width: 100%;
}

.column.is-8 {
  width: 66.66667%;
}

.column.is-4 {
  width: 33.33333%;
}

.box-1 {
  background-color: red;
  height: 200px;
}

.box-2 {
  background-color: yellow;
  height: 400px;
}


.box-3 {
  background-color: blue;
  height: 800px;
}

*,
*::before,
*::after {
  box-sizing: inherit;
}
  <div class="columns">
  <div class="column is-8">
    <div class="box-1">Box 1</div>
    <div class="box-3">Box 3</div>
  </div>
  <div class="column is-4">
    <div class="box-2">Box 2</div>
  </div>
</div>
like image 134
lefanous Avatar answered Jan 27 '23 06:01

lefanous


here is another possibility with grid and auto-fit (see comment in CSS for the setting)

Snippet to run in full page and resize to see behavior.

.columns {
  display: grid;
  /*Below : 400px for minmax  is more than a third  of 1000px width of the container
  to draw at most 2 columns */
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  width: 800px;
  margin: auto;
  max-width: 100%;
}

.column {
  border: solid;
}

.box-1 {
  background-color: red;
  height: 100px;
}

.box-2 {
  background-color: yellow;
  min-height: 100px;
  grid-row: span 2;
}

.box-3 {
  background-color: blue;
  height: 300px;
}
<div class="columns">
  <div class="column is-8 box-1">
    Box 1
  </div>
  <div class="column is-4 box-2">
    Box 2
  </div>
  <div class="column is-8 box-3">
    Box 3
  </div>
</div>
like image 34
G-Cyrillus Avatar answered Jan 27 '23 06:01

G-Cyrillus