Home > Enterprise >  How do I fit header and img in div with set width and height with flex?
How do I fit header and img in div with set width and height with flex?

Time:05-20

I have an assignment where I need to fit an image and header into a div with a fixed width that changes heights every time. It needs to look like the screenshot below, but I have no idea how to get that look.

The sections are where the flexbox starts and I organized the child elements to appear like they should, but everything inside of that, I can't get to work. HTML

<main >
      <section ></section>
      <section >                                  
         <div  style="width: 200px; height: 280px;">  
             <img src="littlecolorado.jpg">                
             <h2>Another card</h2></div>                    
       </section>
    </main>

CSS

    .col-grid {
  display: flex;
  flex-flow: column wrap;
  gap: 20px;
  height: 2000px;
}
.col-grid div img {
  width: 200px;
}
.col-grid div h2 {
  display: block;
}

My file:

my file

What it should look like:

what it should look like

CodePudding user response:

Just setting the height of the image to 100% should do it. That means the image will take up 100% of the available space. If you want more direct control of the growth and shrinking of the children use flex-shrink and flex-grow.

https://codepen.io/gallagher7788/pen/bGLRGLx https://css-tricks.com/understanding-flex-grow-flex-shrink-and-flex-basis/

Note: height:100%;width:100% will distort your image, but thats how the example you included did it. You could create a div with a background image and use background-size:cover to crop the image.

  • Related