object-fit: cover
จะทำสิ่งที่คุณต้องการ
แต่มันอาจไม่ทำงานบน IE / Edge ติดตามที่แสดงด้านล่างที่จะแก้ไขได้ด้วยเพียง CSSในการทำงานในทุกเบราว์เซอร์
วิธีที่ฉันใช้คือจัดตำแหน่งภาพภายในคอนเทนเนอร์ด้วย สัมบูรณ์แล้ววางลงที่กึ่งกลางโดยใช้ชุดค่าผสม:
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
เมื่ออยู่ตรงกลางฉันจะให้ภาพนั้น
// For vertical blocks (i.e., where height is greater than width)
height: 100%;
width: auto;
// For Horizontal blocks (i.e., where width is greater than height)
height: auto;
width: 100%;
สิ่งนี้ทำให้ภาพได้รับผลกระทบจาก Object-fit: cover
นี่คือการสาธิตของตรรกะข้างต้น
https://jsfiddle.net/furqan_694/s3xLe1gp/
ตรรกะนี้ใช้ได้กับทุกเบราว์เซอร์
รูปภาพต้นฉบับ

ตัดแนวตั้ง

ครอบตัดแนวนอน
