Robert van Dijk
Robert van Dijk

Reputation: 23

Why does using flex wrap break the height of an item containing large images?

I have set up a simple page using a container with Flexbox enabled and 2 child divs.

Sizes are set using view width and view height for the container.

Child divs are set to a 600px and 400px width using css flex shorthand.

A large image has been added to child one and resized to 100%.

This works perfectly until flex-wrap: wrap is enabled on the container.

Then the height of the children are suddenly to big.

Is there a way to fix this behaviour?

Below is my code.

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.flex-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
}

.flex-item1 {
  flex: 1 1 600px;
  padding: 20px;
  background-color: coral;
}

.flex-item2 {
  flex: 1 1 400px;
  padding: 20px;
  background-color: cornflowerblue;
}

.image {
  height: 100%;
  width: 100%;
  object-fit: contain;
}
<div class="flex-container">
  <div class="flex-item1">
    <img src="https://picsum.photos/1000/2000" class="image" alt="image" />
  </div>
  <div class="flex-item2">
    <h1>Header 1</h1>
  </div>

Upvotes: 2

Views: 2125

Answers (1)

Michael Benjamin
Michael Benjamin

Reputation: 371113

Just add this to your code:

.flex-item1 {
   height: 100%;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.flex-container {
  width: 100vw;
  height: 100vh;
  display: flex;
  flex-wrap: wrap;
}

.flex-item1 {
  flex: 1 1 600px;
  padding: 20px;
  background-color: coral;
  height: 100%; /* new */
}

.flex-item2 {
  flex: 1 1 400px;
  padding: 20px;
  background-color: cornflowerblue;
}

.image {
  height: 100%;
  width: 100%;
  object-fit: contain;
}
<div class="flex-container">
  <div class="flex-item1">
    <img src="https://picsum.photos/1000/2000" class="image" alt="image" />
  </div>
  <div class="flex-item2">
    <h1>Header 1</h1>
  </div>


With a single line flex container (flex-wrap: nowrap), the height: 100% on the container is recognized by the height: 100% on the image (2 levels down).

With a multi-line flex container (flex-wrap: wrap), the height: 100% on the container isn't inherited by the image. The percentage height chain breaks. So you need to add height: 100% to the middle link (the flex item), for the layout to work in both cases.

Not exactly sure why this happens. Would have to research it.

Upvotes: 2

Related Questions