McKabue
McKabue

Reputation: 2222

Responsive Image with correct aspect ratio in Flex-box

I cannot seem to achieve a responsive image inside a flex-box item correctly. If the image is one of the flex-box item, it works well (Jsfiddle)

.parent {
  display: flex;
  width: 100%;
}
.parent input {
  flex: 1;
}
.parent input:focus + img {
  display: none;
}
<div class="parent">
<img src="https://png.icons8.com/metro/40/000000/graduation-cap.png">
<input />
<img src="https://png.icons8.com/metro/40/00000/user.png">
</div>

When the image is inside a flex item, it starts to misbehave.

Scenario 1: Image stretches distorting the aspect ratio (Jsfiddle)

.parent {
  display: flex;
  width: 100%;
  height: 40px;
}
.parent input {
  flex: 1;
}
.parent input:focus + div {
  display: none;
}
.parent img {
  height: 100%;
  max-height: 100%;
  width: auto;
}
.parent .funny {
  display: flex;
}
<div class="parent">
<img src="https://png.icons8.com/metro/40/000000/graduation-cap.png">
<input />
<div class="funny">
<img src="https://lh3.googleusercontent.com/-OX10v8tUiCY/AAAAAAAAAAI/AAAAAAAADE8/QcezYUDPvxU/s96-c/photo.jpg">
</div>
</div>

Scenario 2: Image leaves empty space (Jsfiddle)

.parent {
  display: flex;
  width: 100%;
  height: 40px;
  background: red;
}
.parent input {
  flex: 1;
}
.parent input:focus + div {
  display: none;
}
.parent img {
  height: 100%;
  max-height: 100%;
  width: auto;
}
.parent .funny {
  display: flex;
}
<div class="parent">
<img src="https://png.icons8.com/metro/40/000000/graduation-cap.png">
<input />
<div class="funny">
<div>
<img src="https://lh3.googleusercontent.com/-OX10v8tUiCY/AAAAAAAAAAI/AAAAAAAADE8/QcezYUDPvxU/s96-c/photo.jpg">
</div>
</div>
</div>

Scenario 3: The layout is good until the input receives focus, then verything breaks: Jsfiddle

This happens in IE 11, Chrome (Version 67.0.3396.87 (Official Build) (64-bit)), but haven't tested in Firefox and Edge.

Is there something i haven't studied about Flex-box, or is it a bug?

Upvotes: 2

Views: 2106

Answers (2)

Swati Anand
Swati Anand

Reputation: 899

The below code seems to be working fine for me. I've just set the image height and width in your first example.

.parent {
  display: flex;
  width: 100%;
}
.parent input {
  flex: 1;
}
.parent input:focus + img {
  display: none;
}

img {
  height: 40px;
  width: auto;
}
<div class="parent">
<img src="https://png.icons8.com/metro/40/000000/graduation-cap.png">
<input />
<img src="https://lh3.googleusercontent.com/-OX10v8tUiCY/AAAAAAAAAAI/AAAAAAAADE8/QcezYUDPvxU/s96-c/photo.jpg">
</div>

For the second example that you shared, again just setting the img height to 40px instead of making it as 100% seems to be working for me. Check the fiddle

Same with scenario 3. Check the fiddle

Upvotes: 1

Deepak gupta
Deepak gupta

Reputation: 554

You have added only one image in <div>.

Check out this fiddle

Upvotes: 0

Related Questions