Home >Web Front-end >CSS Tutorial >How Can I Resize and Crop Images to Specific Dimensions Using Only CSS?
Displaying Resized and Cropped Images with CSS
Requirement: Display an image from a URL with specified width and height, regardless of its original aspect ratio. The image should be resized and then cropped to fit the desired dimensions.
Solution: Combine the img and background-image properties:
Example:
Consider an image with dimensions 800x600 pixels that we want to display as 200x100 pixels.
HTML:
<div class="crop"> <img src="https://i.sstatic.net/wPh0S.jpg" alt="Donald Duck"> </div>
CSS:
.crop { width: 200px; height: 150px; overflow: hidden; } .crop img { width: 400px; height: 300px; margin: -75px 0 0 -100px; }
Explanation:
This approach allows you to resize and crop images dynamically, ensuring they are displayed in the desired size and aspect ratio on various devices.
The above is the detailed content of How Can I Resize and Crop Images to Specific Dimensions Using Only CSS?. For more information, please follow other related articles on the PHP Chinese website!