Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

วิธีป้องกันไม่ให้รูปภาพ Stretch ด้วย Flexbox

เรียนรู้ป้องกัน CSS Flexbox ยืดรูปภาพแนวนอน

Flexbox มี default behavior แปลก: images stretched horizontally เต็ม parent container width ถ้ามี parent element (flex container) flex-direction: column และ child element (flex item) เป็นรูปภาพ รูปจะ maintain natural height แต่ width stretched กว้างเท่า parent container

Behavior นี้ inconsistent ขึ้นอยู่กับ browser default CSS stylesheet (User Agent Stylesheet)

แก้ง่าย: แทนที่ image/flex item align-self property default stretch value ด้วยค่าอื่น

แทน stretch ใช้ center จะลบ image stretching และ vertically align รูปกลาง parent container

img { align-self: center; }

Example

CSS example: 1 parent (flex container) 2 children image elements (flex items)

  • Image แรก: browser default align-self: stretch ทำลาย aspect ratio
  • Image ที่สอง: เพิ่ม utility class .self-center มี align-self: center ลบ stretching:

https://codepen.io/StrengthandFreedom/pen/qBBoMOX

Glorious, problem solved!

หมายเหตุ: ใช้ top ได้อีก ทำให้ vertically align รูปไป top ของ parent container

img { align-self: top; }

ทั้งคู่นำ stretch ออกจากรูป แตะใช้ top หรือ center ขึ้นกับอะไรที่อยากทำกับรูป

ข้อมูลเพิ่มเติม

Flex items มี default align-self value = stretch ไม่ว่า flex-item (child element) จะเป็นรูปหรือ HTML element อื่น จะ stretched horizontally default