Giới thiệu
Thuộc tính object-fit và object-position trong CSS giúp chúng ta cắt ảnh và chỉ định cách hiển thị nó trong một phần tử.
Cú pháp
Cú pháp của thuộc tính object-fit như sau:
Selector {
object-fit: /*giá trị*/
object-position:/*giá trị*/
}
Ví dụ 1: cover vs contain
<!DOCTYPE html>
<html>
<head>
<style>
img {
object-fit: cover;
}
img:last-of-type {
object-fit: contain;
}
</style>
</head>
<body>
cover
<img src="https://images.unsplash.com/photo-1611423837981-2cba00ee7631?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=120&ixlib=rb1.2.1&q=80&w=120" width="200" height="250"/>
<img src="https://images.unsplash.com/photo-1611423837981-2cba00ee7631?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=120&ixlib=rb1.2.1&q=80&w=120" width="200" height="250"/>
contain
</body>
</html>
Kết quả
Đoạn mã trên sẽ cho kết quả sau:

Ví dụ 2: object-position
<!DOCTYPE html>
<html>
<style>
div {
border: 1px solid blue;
width:100%;
height:300px;
}
img {
float:left;
width:50%;
height:100%;
object-fit:cover;
object-position: 20px -10px;
}
</style>
<body>
<div >
<img src="https://images.unsplash.com/photo-1611800065908-233b597db552?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=350&ixlib=rb1.2.1&q=80&w=250" />
<img src="https://images.unsplash.com/photo-1612626256634-991e6e977fc1?crop=entropy&cs=tinysrgb&fit=crop&fm=jpg&h=350&ixlib=rb1.2.1&q=80&w=250"/>
</div>
</body>
</html>
Kết quả
Đoạn mã trên sẽ cho kết quả sau:

Hiệu ứng khi thay đổi kích thước:
