I'd like to resize and crop an image of unknown dimensions, just with css. The image should be resized/cropped to completely fill a container of known dimensions, cutting off as little of the image as possible.
Also, if an image is cropped then I'd like to determine, for example, that the center of the image should be shown, not the top left.
I made a jsfiddle illustrating the issue: http://jsfiddle.net/q9jFx/
I can, for example, set image width to 100%, but that doesn't work if the image is wider than it is tall.
.container { width: 180px; height: 160px; overflow: hidden; border:red solid 2px }
.container img { width:100%}
<div class="container">
<img src="the_src" alt="alt" />
</div>
The modern way is to use object-fit: none; (or the more common object-fit: cover; if you want to scale, but without stretching). 97% of browser sessions support this as of 2022 May.
One of the simplest ways to resize an image in the HTML is using the height and width attributes on the img tag. These values specify the height and width of the image element. The values are set in px i.e. CSS pixels.
The only way you can achieve this only using css is to use the CSS background
property combining it with the background-size
and background-position
properties.
SEE THIS FIDDLE
More information for these properties :
background-position
background-size
HTML:
<div class="container" style="background-image:url(http://www.recipestap.com/wp-content/plugins/wp-o-matic/cache/af4e1_ap.jpg)"></div>
<div class="container" style="background-image:url(http://3.bp.blogspot.com/-LAfvYIuz6c4/UpQxIe-FlmI/AAAAAAAAAcE/DVeCw1W6Yu4/s320/Eggless+Mini+Apple+Pie.JPG)"></div>
CSS:
.container {
width: 180px;
height: 160px;
border:red solid 2px;
/* add following */
background-size:cover;
background-position:50% 50%;
}
ADDITIONAL INFORMATION
If you realy need the <img>
tag for SEO reasons or other, you will need JS to face all the cases you may come through.
CASE 1 : image ratio is wider than container
Use height:100%;
and width:auto;
then you will need JS again to center the image in the container.
CASE 2 : image ratio is heigher than the container
Use width:100%;
and height:auto;
then JS or display:table;
/display:table-cell
to verticaly center the image in container.
I have used this technique on some projects but it is pretty heavy compared to the background
CSS technique.
You can set Image width and Height
### please Try It: http://jsfiddle.net/q9jFx/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With