Search code examples
htmlcssflexbox

How to set a specific size of a flex box container?


As the title states, I want the container of a flexbox to have a specific width and height. However, I don't know what approach I can use. This is my code:

<div class="container-gallery">
  <img src="gallery/img.png" alt="">
  <img src="gallery/img1.jpg" alt="">
  <img src="gallery/img2.jpg" alt="">
  <img src="gallery/img3.jpg" alt="">
  <img src="gallery/img4.jpg" alt="">
  <img src="gallery/img5.jpg" alt="">
</div>
.container-gallery {
  display: flex;
  flex-wrap: wrap;
  /* width: 67.5%; */
  justify-content: center;      
}

.container-gallery img{
  width: 15%;
  height: 30vh;
  border-radius: 8%;
  margin: 1%;
}

I tried creating a parent div of the container gallery to center the children div and put a specific width in container-gallery. It does work; however, when you try resizing it, it doesn't center its content because of the set width on it. Something like this:

<div class="container-gallery">
  <img src="gallery/img.png" alt="">
  <img src="gallery/img1.jpg" alt="">
  <img src="gallery/img2.jpg" alt="">
  <img src="gallery/img3.jpg" alt="">
  <img src="gallery/img4.jpg" alt="">
  <img src="gallery/img5.jpg" alt="">
</div>
.container-gallery {
  display: flex;
  flex-wrap: wrap;
  width: 67.5%;
}

.container-gallery img{
  width: 15%;
  height: 30vh;
  border-radius: 8%;
  margin: 1%;
}

.main-gallery {
  display: flex;
  justify-content: center;
}

What can I do?
I'm pretty new to Flexbox so treat this as a newbie question.

It should be like this! the width and height. desire output


Solution

  • The below CSS fixed your issue!

    please view in full screen for proper results!

    flex-grow: 0

    flex-shrink: 0

    flex-wrap: 30.33%

    The reason its not 33.33% or 1/3 is because to adjust for the margin!

    html,
    body {
      background-color: #191D2B;
      margin: 0px auto;
      padding: 0px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex-direction: column;
    }
    
    .title {
      font-size: 50px;
      color: white;
    }
    
    .container-gallery {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
    
    .container-gallery img {
      flex: 0 0 30.33%;
      border-radius: 8%;
      margin: 5px;
    }
    
    .main-gallery {
      display: flex;
      justify-content: center;
    }
    <div class="title">Gallery</div>
    <div class="container-gallery">
      <img src="https://placehold.co/200x200" alt="">
      <img src="https://placehold.co/200x200" alt="">
      <img src="https://placehold.co/200x200" alt="">
      <img src="https://placehold.co/200x200" alt="">
      <img src="https://placehold.co/200x200" alt="">
      <img src="https://placehold.co/200x200" alt="">
    </div>