Search code examples
csslayoutflexboxresponsive-design

Flexbox positioning of elements


Hi this is my example layout on mobile device.

https://codesandbox.io/s/cocky-dust-xuurof?file=/src/styles.css

On the wider screen the third element must be the same width like a second yellow element. The second and the third element. The second and third items together are the same height as the first item. The html structure cannot change, I need use Flexbox, not css grid.

.App {
  font-family: sans-serif;
  text-align: center;
  display: flex;
  border: 2px solid black;
  flex-wrap: wrap;
}

.one {
  background-color: red;
  flex-basis: 120px;
  height: 80px;
}

.two {
  background-color: yellow;
  flex-grow: 1;
}

.three {
  background-color: green;
  height: 30px;
  flex-basis: 100%;
}

@media only screen and (min-width: 500px) {
  .one {}
  .two {}
  .three {}
}
<div class="App">
  <div class="one">1</div>
  <div class="two">2</div>
  <div class="three">3</div>
</div>


Solution

  • I modified the media query to account for this snippet.

    You should see "Large Screen" results in the snippets "Full Page" mode.

    .App {
      font-family: sans-serif;
      text-align: center;
      display: flex;
      border: 2px solid black;
      flex-wrap: nowrap;
    }
    
    .one {
      background-color: red;
      width: 120px;
      height: 80px;
      align-items: stretch;
    }
    
    .two {
      background-color: yellow;
      flex: 4 1 auto;
    }
    
    .three {
      background-color: green;
      height: initial;
      flex: 4 1 auto;
    }
    
    @media screen and (width < 1024px) {
      .App {
        flex-wrap: wrap;
      }
      .two {
        flex: 4 0 auto;
      }
      .three {
        height: 30px;
        flex: 4 0 100%;
      }
    }
    <div class="App">
      <div class="one">1</div>
      <div class="two">2</div>
      <div class="three">3</div>
    </div>