andyg1
andyg1

Reputation: 1543

Responsive images, without being 100% width if the container is bigger - containers are flexbox

I have a two column layout - fixed right column width, an scalable content in the left column.

The layout scales great with different screen sizes until I add images to the scalable column. If the container goes down to the size of the image it pushes the column too wide, squashing my 300px right column.

I set

width:100%;

on the images, which solves the responsiveness issue, but when the container is full screen again the images scale to fill it, which is not what I want because it looks rubbish. I've added

max-width:100%;

which hasn't helped.

In short, I want the image behaviour to be "Be your real size, unless the container is smaller, in which case shrink."

(I should mention that my two-column layout is done with flexbox)

Edit: After playing around with this for ages, it turns out to be a difference in behaviour between broswers - Chrome scales the container, shrinking the image (as per max-width) but Firefox just pushes all the content out. Open this in each: https://jsfiddle.net/andyg1/sb7zefr5/

Upvotes: 2

Views: 2828

Answers (5)

andyg1
andyg1

Reputation: 1543

After identifying that the problem is different between Firefox and Chrome I did some research to find out that the problem can be fixed by adding:

min-width:0;

to the element containing the responsive. As discussed here: Firefox flexbox image width

Upvotes: 1

zer00ne
zer00ne

Reputation: 43880

You can use an image as a background to your flex-item.

background-image, background-repeat, background-position, and most importantly background-size

* {
  margin: 0;
  padding: 0;
}
body {
  width: 100vw;
  height: 100vh;
}
.flex {
  display: flex;
  justify-content: center;
  width: 100%;
  height: 100%;
}
.bg {
  width: 50vw;
  height: 50vh;
  background: url(https://upload.wikimedia.org/wikipedia/en/2/24/Lenna.png) no-repeat center;
  background-size: contain;
  outline: 3px dashed red;
  flex: 1 0 50%;
}
.rt {
  width: 300px;
  height: 50vh;
  outline: 3px dashed blue;
}
<div class="flex">
  <figure class="bg"></figure>
  <figure class="rt"></figure>
</div>

Upvotes: 1

Ismail Farooq
Ismail Farooq

Reputation: 6807

Add display:block to image.

.my_image {
    display:block;
    max-width:100%;
    height:auto;
}

Upvotes: 0

Johannes
Johannes

Reputation: 67748

You can use width: 100% and the real size if the image or the maximum size of the conainer as max-width, for example

my_image {
  width: 100%;
  max-width: 320px;
}

That way it will shrink with the container, but not grow above a set size.

Upvotes: 1

fnune
fnune

Reputation: 5494

Remove width:100%; and keep max-width:100%;. This will keep images at their original size but shrink them to 100% width if the container is smaller.

Here's an example https://jsfiddle.net/v4kL409v/

Upvotes: 2

Related Questions