技術共有

CSS は画像のトリミングと中央揃えを実装します (トリミングされた画像の中央部分のみがキャプチャされ、画像は変形されません)

2024-07-12

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

1. 最初の方法: (画像を直接設定します: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. 2 番目の方法 (画像を設定します: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

ここに画像の説明を挿入します

完了〜