skip to Main Content

I have a flex-container where some of the items are divs that have images as background:

.column_flex_container {
  display: flex;
  flex-direction: column;
}

.flex_image {
  width: 100%;
  background-image: url("my_img.png");
  background-repeat: no-repeat;
}
<div class="column_flex_container">
  <div class="flex_item flex_image">

  </div>
</div>

Since the height is not set, it will be 0. But how can I make it set the height according to the width and resolution?

So that the image will fit the 100% width of the flex container and change the height dynamically without losing its aspect-ratio.

Is it possible?

2

Answers


  1. maybe try this height: max-content;

    Login or Signup to reply.
  2. try this:

    .column_flex_container {
      display: flex;
      flex-direction: column;
    }
    
    .flex_image {
      width: 100%;
      background-image: url("my_img.png");
      background-repeat: no-repeat;
      background-size: cover;
      padding-bottom: 56.25%;
    }
    

    if the aspect ratio of the image is 16:9, set the padding-bottom of the flex item to 56.25% (9 divided by 16 times 100)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search