Yamen
Yamen

Reputation: 51

right and left padding in a flexbox container is stretching the child image

I have a flexbox, direction column, with four children, an image and three text elements. The image has correct proportions when there's no padding in the container, but the more right and left padding I add in the container, the more vertically stretched the image gets. This is only happening on mobile devices, iPhone, iPad, etc. It's as if the flexbox is treating the image as a text element, with more padding it stretches it to fit more content.

align-self: center; and align-items: center; are not working in this case

Here's a simplified code.

<li class="painting" > 
   <img src="src">
   <h5 class="Title">{{title}}</h5>
   <p class="Summary">{{summary}}</p>
   <p class="Price">Price: {{price}}</p>
</li>

the CSS

li{
    width: 22%;
    margin: 3vh 2%;
    padding: 1% 2%;
    display: flex;
    flex-direction: column;
}
img{
    width: 100%;
    height: auto;
    margin: auto 0;
    align-self: center;
    flex: 0 0 auto;
}
h5{
    margin: 1rem 0 0 0;
    padding: 0 0 0.5rem 0;
}
p{
    margin: 1rem 0 0 0;
    white-space: pre-wrap;
    flex-shrink: 1; 
}

Wrapping the image in a non-flex container solves the problem, but I would like to understand the problem. I don't get this behaviour and why exactly it happens on mobile devices. Could anyone shed some light on the issue?

Upvotes: 0

Views: 859

Answers (2)

Aniket K
Aniket K

Reputation: 434

You can make use of the object-fit property to avoid stretching the image.

Note: Avoid assigning percentage values for padding, margin etc. You can always make use of media-query for responsive padding.

Upvotes: 1

Aron
Aron

Reputation: 150

To prevent your child image being stretched set a width on the image tag then constrain the width in css.

HTML:

<img src="src" width="400">

Then change your CSS:

img {
max-width: 100%;
}

Upvotes: 0

Related Questions