Search code examples
htmlcssflexbox

Why is my flexbox container wrapping my divs on the big sceen and not only on the small one?


just getting started with flexbox. After managing to align img div and text div, I added the "flex-wrap:wrap" to the container so that img and text would be stacked on top of each other on smaller screens. Now they are always stacked on top of each other. Why? Do I need a media query?

.banner-container{
  display: inline-flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  flex-direction: row;
}

.intro-text{
  border: 2px solid blueviolet;
  margin: 10px;
}

.banner-img{
  border: 2px solid blue;
  max-width: 50%;
  margin: 10px;
}

.banner-img img{
  width: 100%;
  height: auto;
}
  
<div class="banner-container">
            <div class="banner-img">
                <img src="https://www.region-muenchen.com/fileadmin/region-muenchen/Dateien/Fotos_Abb/Landkreiskarten/DAH_Ausschnitt.jpg" alt="map Dachau area">
            </div>
            <div class="intro-text">
                <h1>Something</h1>
                <h4>Something Something Something Something Something Something Something Something Something Something Something Something Something Something Something Something </h4>
            </div>
        </div>

I was expecting to stack my divs only when there isnt enough space to display them next to each other.


Solution

  • Here's the code, refined:

    .banner-container{
        display: inline-flex;
        flex-direction: row;
        flex-wrap: wrap;
        align-items: center;
        justify-content: center;
    }
    
    /*this is the only code you need to add */
    .banner-container div {
        min-width: 400px; /*you can change this value*/
        flex: 0 0 40%;
    }
    
    .intro-text{
      border: 2px solid blueviolet;
      margin: 10px;
    }
    
    .banner-img{
      border: 2px solid blue;
      max-width: 50%;
      margin: 10px;
    }
    
    .banner-img img{
      width: 100%;
      height: auto;
    }
    <div class="banner-container">
                <div class="banner-img">
                    <img src="https://www.region-muenchen.com/fileadmin/region-muenchen/Dateien/Fotos_Abb/Landkreiskarten/DAH_Ausschnitt.jpg" alt="map Dachau area">
                </div>
                <div class="intro-text">
                    <h1>Something</h1>
                    <h4>Something Something Something Something Something Something Something Something Something Something Something Something Something Something Something Something </h4>
                </div>
            </div>  

    Explanation:

    Setting 'min-width' will make sure that child divs take the least needed width, and if is not fitting, then it will stack. Setting 'flex: 0 0 40%' will make sure the child divs are one beside the other on larger screens.

    I hope this helps! :)