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

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

Barbara Streisand
Release: 2024-12-27 07:23:09
Original
511 people have browsed it

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

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:

  • Resizing: Use the HTML img element's width and height properties to resize the image. This will maintain the original image's aspect ratio.
  • Cropping: Create a container element (e.g., a div) with the desired final dimensions. Set an overflow of hidden for this container to crop any excess image.

Implementation:

.crop {
  width: 200px;
  height: 150px;
  overflow: hidden;
}

.crop img {
  width: 400px;
  height: 300px;
  margin: -75px 0 0 -100px;
}
Copy after login
<div class="crop">
  <img src="https://i.sstatic.net/wPh0S.jpg" alt="Image">
</div>
Copy after login

In this example:

  • The image will be resized to a width of 200px and a height of 150px (with aspect ratio maintained).
  • The margin property is used to crop the image by shifting its position within the container.
  • The container's overflow property is set to hidden to ensure that only the desired portion of the image is displayed.

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template