For details, please refer to: https://timor419.github.io/2020/04/19/CSS-img/
Statement of needs:
There are generally two ways to achieve the effect of making a rectangular image display a square without deformation. One is to set it as a background image, and the other is to use the img tag.
Original image ↓:
Background image ↓:
1. Background image
First of all, let's take a look at how to achieve our needs by setting the background image, mainly through the background-size attribute to set the scaling of our background image.
Briefly introduce background-size:
background-size: contain; Automatically adjust the zoom ratio to ensure that the picture is always completely displayed in the background area without cropping the picture
background-size: cover; The image is proportionally scaled, and if there is overflow, it will be cropped and hidden
Not much to say, directly on the code:
HTML
<div class="bgc"></div>
CSS
.bgc {
width:500px;
height: 500px;
background: url("images/1.jpeg") no-repeat center;
background-size: cover;
}
Two, img tag
In the development process, it is often necessary to display the image returned by the backend as a square without deformation. We will use the img tag, mainly through the object-fit attribute of css.
HTML
<img src="images/1.jpeg" class="img">
CSS
.img{
width:500px;
height: 500px;
object-fit: cover;
flex: 1;
}
------------- The End -------------
License Agreement: For reprinting, please keep the original link and author.