Home > Web Front-end > CSS Tutorial > How Can I Resize and Crop Images Using HTML and CSS While Maintaining Aspect Ratio?

How Can I Resize and Crop Images Using HTML and CSS While Maintaining Aspect Ratio?

Barbara Streisand
Release: 2024-12-25 09:35:00
Original
206 people have browsed it

How Can I Resize and Crop Images Using HTML and CSS While Maintaining Aspect Ratio?

Displaying a Resized and Cropped Image with CSS

Introduction

Displaying images within specific dimensions while maintaining their aspect ratio can be challenging. This article explores how to effectively resize and crop an image using a combination of HTML and CSS techniques.

Background Image Resizing

The background-image property allows us to specify an image as the background of a container element. By setting the background-size property to cover, the image will resize automatically to fit the container while maintaining its ratio.

Image Resizing

The tag can be used to embed an image within a webpage. By specifying the width and height attributes, we can explicitly set the desired dimensions. However, this may distort the image if the original aspect ratio is not maintained.

Combining Techniques

To achieve both resizing and cropping, we can combine the above methods. We create a container element with the background-image property set and the desired background size. Inside the container, we place an element with dimensions smaller than the container. By carefully adjusting the margin properties of the element, we can effectively crop the image to the desired size while maintaining its original aspect ratio.

Example

The following code demonstrates how to resize and crop an image:

.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="Your image">
</div>
Copy after login

In this example, the container element (

) with dimensions 200px by 150px contains an image () with dimensions 400px by 300px. By setting overflow to hidden on the container, the image is cropped, and by manipulating the margin properties of the element, the resulting image is effectively resized and cropped to fit the container while preserving its aspect ratio.

The above is the detailed content of How Can I Resize and Crop Images Using HTML and CSS While Maintaining Aspect Ratio?. 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