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

วิธีสร้าง Responsive Image (รูปภาพตอบสนอง) ด้วย CSS

ทำให้รูปภาพปรับขนาดอัตโนมัติตาม Container โดยไม่ล้นออกนอกหน้าจอ ใช้ max-width: 100% และ width: 100%

ตัวอย่างโค้ด

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> img {    width: 100%;    max-width: 1000px; } </style> </head> <body> <h1>Responsive Images Example</h1> <h2>Resize the window to see responsive image scale up and down</h2> <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"> </body> </html>

คำอธิบาย

  • width: 100% - รูปขยายเต็มความกว้าง Parent
  • max-width: 1000px - แต่ไม่เกิน 1000px (ขนาดต้นฉบับ) ป้องกัน Blur/Pixelate
  • height: auto (Default) - ความสูงปรับอัตโนมัติรักษาสัดส่วน

Best Practice: Responsive Images แบบสมัยใหม่

<img src="small.jpg" 
     srcset="small.jpg 480w, medium.jpg 800w, large.jpg 1200w"
     sizes="(max-width: 600px) 100vw, 50vw"
     alt="Description">
  • srcset - ให้ Browser เลือกรูปที่เหมาะกับหน้าจอ/ความหนาแน่น
  • sizes - บอก Browser ว่ารูปจะแสดงกว้างเท่าไหร่ในแต่ละ Breakpoint
  • ประหยัด Bandwidth โหลดเร็วขึ้นบน Mobile

ผลลัพธ์

รูปภาพปรับขนาดตามหน้าต่างเบราว์เซอร์: ใหญ่บน Desktop, เล็กลงบน Mobile ไม่ล้นจอ