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

วิธีจัดกึ่งกลางรูปภาพ (Center Image) ด้วย CSS

เทคนิคคลาสสิกการจัดรูปภาพให้อยู่กึ่งกลางแนวนอน ใช้ display: block และ margin-left/right: auto

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

<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> img {    display: block;    margin-left: auto;    margin-right: auto;    width: 50%; } </style> </head> <body> <h1 style="text-align: center;">Example of centering an image</h1> <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"> </body> </html>

ทำไมต้อง display: block?

  • <img> เป็น Inline Element ต้นฉบับ (เหมือนตัวอักษร)
  • Inline Element ไม่รับ margin-left/right: auto
  • display: block ทำให้มันกลายเป็น Block Element จึงจัดกึ่งกลางได้ด้วย Auto Margin

วิธีอื่นๆ

วิธีCSS
Flexbox (บน Parent).container { display: flex; justify-content: center; }
Grid (บน Parent).container { display: grid; place-items: center; }
Text-align (บน Parent).container { text-align: center; } img { display: inline-block; }
Margin Auto (ตัวเอง)img { display: block; margin: 0 auto; }

ผลลัพธ์

รูปภาพกว้าง 50% ของ Container จัดอยู่กึ่งกลางแนวนอนพอดี