0

I have a situation like the one below. I'd like to have a container into which I'll be putting an image (it could be horizontal or vertical, or square). I want it to stay within the main-container, and take 80% of it. I'm using flexbox to achieve it. However, it doesn't seem to work. The image goes out of the main-container.

I found various solutions online of how to achieve it. In this example I'm using suggestion that I found here: https://www.tutorialrepublic.com/faq/how-to-auto-resize-an-image-to-fit-into-a-div-container-using-css.php.

Basically I added this to my image:

max-width: 100%;
max-height: 100%;
display: block;

In my "real" code, I'm also using grid around all that. However, I didn't want to add too much stuff here, and I know very well how CSS can become a "monster" when too many things are combined. When I understand this smaller problem, I'll move on to the more complex one :)

* {
  box-sizing: border-box;
}

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

.main-container {
  height: 200px;
  width: 200px;
  background: blue;
  
  display: flex;
  flex-direction: column;
}

.img-container { 
  background: green;
  flex: 8;
}

.my-img {
  max-width: 100%;
  max-height: 100%;
  display: block;
}

.text {
  flex: 1;
}
<div class="main-container">
  <div class="img-container">
    <img class="my-img" src="https://dummyimage.com/400x600/b84db8/ffffff.jpg"/>
  </div>
  <div class="text">Line 2</div>
  <div class="text">Line 3</div>
</div>
mnj
  • 2,539
  • 3
  • 29
  • 58

0 Answers0