Eoin
Eoin

Reputation: 301

Why does the actual width of a scaled image inside a flex item affect item's width?

I was trying to achieve a header with a height proportional to the screen and containing an image with a title. The attempted solution used a row flex layout. The intention is to have the header a proportion of the viewport/parent height (20%). The width of the image and its parent should match the scaled image width according to the image's aspect ratio. The title's parent div should occupy the remaining width and grow to fill any available horizontal space.

The container is using fixed positioning with a proportional height.

The actual behaviour in Chrome 54 and Firefox 50 is that the image's parent element occupies most of the container width and this width is dictated by the image's actual width (not the scaled width of the image). I don't understand this when the image is scaled down to a fraction of that width.

Example reproducing this behaviour here: https://jsfiddle.net/uy66as8k/

HTML:

<div class="container">
  <div class="img-view">
    <img src="http://lorempixel.com/800/600/"></img>
  </div>
  <div class="title-view">
    <h1>This is the Title</h1>
  </div>
</div

CSS:

.container {
  display: flex;
  flex-direction: row;
  width: 100%;
  height: 20%;
  margin: 0;
  position: fixed;
  left: 0;
  top: 0;
}

.img-view {
  background-color: salmon;
  flex: 0 0 auto;
}

.title-view {
  background-color: cyan;
  flex: 1 0 auto;
}

img {
  max-height: 100%;
  max-width: 100%;
}

Desired result: enter image description here

Actual result: Actual result

Upvotes: 3

Views: 199

Answers (1)

Carl Edwards
Carl Edwards

Reputation: 14434

Just set your image container to have a height of 100%.

.img-view {
  height: 100%;
  ...
}

Explanation: Okay so first and foremost you have your container set at 20% of whatever its parent is. In this case its the body. You're pulling in images with random dimensions so you're encountering a situation where their dimensions are exceed their parent containers (.container, .image-view).

The max-height/max-width properties that are assigned to all the images won't know its max until you explicitly set a height on its parent (.image-view). Once that's done it'll constrain itself properly as seen in the fiddle below.

https://jsfiddle.net/uy66as8k/3/

Upvotes: 1

Related Questions