Display an Image Resized and Cropped with CSS
Problem:
You want to display an image from a URL at a specific width and height, even if its aspect ratio differs from the desired dimensions. The goal is to resize the image while maintaining its original ratio, and then crop it to the desired size.
CSS Solution:
To achieve both resizing and cropping, you can combine the following techniques:
Implementation:
.crop { width: 200px; height: 150px; overflow: hidden; } .crop img { width: 400px; height: 300px; margin: -75px 0 0 -100px; }
<div class="crop"> <img src="https://i.sstatic.net/wPh0S.jpg" alt="Image"> </div>
In this example:
Result:
This combination allows you to display an image at a specific size while maintaining its original aspect ratio and cropping it to fit your desired dimensions.
The above is the detailed content of How Can I Resize and Crop an Image to Specific Dimensions Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!