Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoid stretch on image css

Tags:

I am rendering an image into a div. I want to avoid stretching of my image.

div {   height: 300px;   width: 300px;  } img {   min-width: 300px;   min-height: 300px;   max-height: 300px;    } 

My problem is that my image's width stretches. I want it to have the regular width even though parts of the image will be missing.

div {   height: 300px;   width: 300px;    overflow: hidden; } img {   height: 300px   max-width: none;   min-width: 300px; } 
like image 650
Zincktest Avatar asked Apr 23 '13 19:04

Zincktest


People also ask

How do I stop my pictures from stretching?

Fortunately, the solution is simple. You just need to replace your image/flex item's align-self property's default stretch value with another value. Instead of stretch you can use center , which will remove the image stretching, and vertically align your image in the middle of its parent container.

How do I stop my div from stretching?

To prevent a div container from streching, when defining the width and height, don't use %, because this means that the width and height of the div is changed based on the width and height of the browser window. Use px instead, and you should not have such issues.

Why is my image stretching?

They are stretched because you specified both width and height attributes for the <img> tag. If the actual image is of different dimensions, one can see how the browser has no options but to distort the image to make it fit the specified height and width.


2 Answers

You can achieve this with simply adding object-fit: cover;. An example might be like -

img {     height: 300px     width: 100%;     object-fit: cover; } 
like image 200
Al Amin Avatar answered Sep 19 '22 18:09

Al Amin


I would forget setting the min-height and the max-height. Just set the height to be 300 pixels and put an overflow hidden on the div tag. That way no matter what the image size it will always stay in proportion and never go outside the boundaries of your div tag.

div { height: 300px; width: 300px; overflow: hidden; } img { height: 300px; } 
like image 34
ZombieCode Avatar answered Sep 19 '22 18:09

ZombieCode