Home >Web Front-end >CSS Tutorial >How Can I Resize and Crop Images to Specific Dimensions Using Only CSS?

How Can I Resize and Crop Images to Specific Dimensions Using Only CSS?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 06:39:101019browse

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:

  • Use img to resize the image while maintaining its aspect ratio.
  • Use background-image to crop the resized image to the desired size.

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:

  • The .crop class defines the container for the image, with its desired width and height.
  • The img element is used to resize the image while preserving its aspect ratio. The width and height are set to maintain the original size ratio.
  • The negative margins are applied to the img element to center and crop it within the .crop container. The margins are calculated based on the full size of the original image (400px x 300px) and the desired display size (200px x 100px).

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn