james156
james156

Reputation: 57

Avoid image stretching

so I have an image tag on my page that is set to 300px height. When a bigger image is used for it, the image is stretched so it fits and it gets really ugly. Is there a way to just get a part of the image instead, preferably the top 300pxs of it?

Hope I made myself clear, I'm new to this. Thank you!

Upvotes: 1

Views: 9929

Answers (5)

I just added this CSS code, and it worked perfectly well. None of the above worked for my case, as my image sizes are different. However, it was very helpful and led me to my solution.

img { max-width: cover; height: auto; }

Upvotes: 0

Stanislas Nanchen
Stanislas Nanchen

Reputation: 111

A possibility is to use the object-fit CSS property on the image. For instance, the value contain will scale down the image so that its original ratio is maintained; while the value cover will crop parts of the image. You can then use the object-position property to properly place the scaled down or the croped image.

For more information on these CSS properties and their differents values:

Upvotes: 2

mjmayank
mjmayank

Reputation: 194

I believe

overflow:hidden;

is what you're looking for. You put that property on a div that surrounds the image, not the image itself. Here's a good resource: http://css-tricks.com/almanac/properties/o/overflow/

Here's a code sample:

<html>
<head>
<style>
.overflow{
    height:100px;
    width:200px;
    overflow:hidden;
}
img{
    height: 200px;
}
</style>
</head>

<body>
<div class="overflow">
<img src="http://funmozar.com/wp-content/uploads/2014/06/white-cat.jpg">
</div>
</body>
</html>

You could also want to consider using the max-height and max-width properties. Make sure not to set both height AND width on the image or it will still stretch it to match those parameters.

Upvotes: 4

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201518

You can wrap the image in an element, set fixed dimensions for the container and no dimension settings for the image but overflow: hidden on the image. Here’s an example of using small dimensions:

An image:<br>
<img src="http://www.lorempixel.com/100/100" alt="foo"><br>
The same image with just the upper half taken:<br>
<div style="width: 100px; height: 50px; overflow: hidden"><img
   src="http://www.lorempixel.com/100/100" alt="foo"></div>

Upvotes: 0

Luigi De Rosa
Luigi De Rosa

Reputation: 720

probably the best solution in order to avoid image stretching is to use a div with fixed size (width and height), background-image and use background-size propriety.

example:

html:

<div id="yourDiv"></div>

css:

#yourDiv {
  width: 200px;
  height: 200px;
  background-image: url('yourimage.jpg');
  background-size: cover;
}

Please have a look here for other information about background-size: https://developer.mozilla.org/en-US/docs/Web/CSS/background-size

Upvotes: 1

Related Questions