Home > database >  How to specify when element should wrap with flexbox?
How to specify when element should wrap with flexbox?

Time:04-23

I have 2 blocks that are wrapped in flex container. I specified so that flex-row will wrap, but is there any way to clearly indicate when should elements wrap? I want to resize content inside flex-items until some breakpoint and only then wrap them.

Code looks like that:

.flex-row{
  display:flex;
  flex-wrap:wrap;
}
<div class='flex-row'>

  <div >

  <h2>Some title</h2>
  <p>Some text</p>
  </div>


  <div >

  <img src="img"/>
    
  </div>


</div>

Appreciate your help. Thank you in advance.

CodePudding user response:

You could use min-width on the blocks. This means they will fully stretch, but when the screen size limits them to being 200px in this example, that breakpoint will lead them to wrap, and their width will never go below 200px.

Another option is to just apply flex-wrap: wrap; on that specific breakpoint you want with a media-query.

For further control, you could also look into flex-basis: https://developer.mozilla.org/en-US/docs/Web/CSS/flex-basis

EDIT: Responsive image

Genereally it's good to include this line of code on most images: max-width: 100%; height: auto; as this will make images auto-responsive. max-width: 100%; forces the image to never overflow from its container, and height: auto; adjusts the images height so its aspect ratio is correct. Try dragging the screen size and you will see its effect :)

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

.block1,
.block2 {
  min-width: 200px;
}

.block2 img {
  max-width: 100%;
  height: auto;
}
<div class='flex-row'>

  <div >

    <h2>Some title</h2>
    <p>Some text</p>
  </div>


  <div >

    <img src="http://via.placeholder.com/350x350" />

  </div>


</div>

CodePudding user response:

Without the flex-wrap property it wont wrap so you can use media querys to exactly define when to wrap the elements. But you also have to set the width for the flex-items.

.flex-row {
  display: flex;
}

/* Wrap */
@media only screen and (max-width: 1023px) {
  .flex-row {
    flex-wrap: wrap;
  }
  
  .block1,
  .block2 {
    width: 100%;
  }
}
<div class='flex-row'>

  <div >
    <h2>Some title</h2>
    <p>Some text</p>
  </div>

  <div >
    <img src="http://via.placeholder.com/350x350"/>
  </div>

</div>

  • Related