Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize and crop image with CSS

Tags:

html

css

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>
like image 886
user984003 Avatar asked Feb 23 '14 10:02

user984003


People also ask

How do I crop instead of resize CSS?

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.

How do I resize an image in HTML CSS?

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.


2 Answers

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.

like image 119
web-tiki Avatar answered Oct 05 '22 02:10

web-tiki


You can set Image width and Height

### please Try It: http://jsfiddle.net/q9jFx/3/
like image 21
user3342524 Avatar answered Oct 05 '22 01:10

user3342524