Tìm hiểu cách ngăn CSS Flexbox stretch ảnh horizontally.
Flexbox có default behavior lạ: images bị stretch horizontally full width của parent container. Vì vậy nếu bạn có parent element (flex container) với flex-direction: column và child element (flex item) là image, thì image's natural height được giữ nhưng width bị stretch rộng bằng parent container.
Behavior này inconsistent, tùy default CSS stylesheet của trình duyệt (User Agent Stylesheet).
May mắn thay, giải pháp đơn giản. Bạn chỉ cần replace image/flex item's align-self property default stretch value bằng giá trị khác.
Thay vì stretch bạn có thể dùng center, sẽ remove image stretching, và vertically align image giữa parent container.
img { align-self: center; }
Ví dụ
Xem CSS example sau: 1 parent (flex container) và 2 children image elements (flex items).
- Image element đầu có browser default
align-self: stretchlàm hỏng aspect ratio. - Image element thứ hai, tôi thêm utility class
.self-center, với declarationalign-self: centerloại bỏ stretching:
https://codepen.io/StrengthandFreedom/pen/qBBoMOX
Glorious, problem solved!
Lưu ý: bạn cũng có thể dùng top, để vertically align image lên top parent container.
img { align-self: top; }
Cả hai methods remove stretch value từ image, nhưng dùng top hay center tùy bạn muốn làm gì với images.
Điều tốt để biết
Flex items có default align-self value là stretch. Vì vậy flex-item (child element) là image hay HTML element khác, nó bị stretch horizontally mặc định.