Technology Sharing

CSS realizes image cropping and centering (only the middle part of the cropped image is captured, and the image is not deformed)

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

1. The first method: (directly set the image:object-fit:cover;

.imgbox{
  	width: 100%;
	height:200px;
	overflow: hidden;
	position: relative;

  img{
	width: 100%;
    height: 100%;  //图片要设置高度
	display: block;
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
    object-fit:cover;  //重要代码
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

2. The second method (set the image:object-fit: none; object-position: 50% 50%;

.imgbox{
  	width: 100%;
	height:200px;
	overflow: hidden;
	position: relative;

  img{
	width: 100%;
    height: 100%; //图片要设置高度
	display: block;
	position: absolute;
	left: 0;
	right: 0;
	top: 0;
	bottom: 0;
	//重要代码
   	object-fit: none; /* 不调整图片大小 */
    object-position: 50% 50%; /* 图片中心对齐盒子中心 */ 
  }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

insert image description here

Done~