สร้าง Portfolio Gallery แบบ Grid Responsive: 4 คอลัมน์บน Desktop, 2 คอลัมน์บน Tablet, 1 คอลัมน์บน Mobile ใช้ Float + Media Query
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> * { box-sizing: border-box; } h1 { font-size: 50px; text-align: center; font-family: monospace, serif, sans-serif; } body { background-color: #f1f1f1; padding: 20px; font-family: Arial; } main { max-width: 1000px; margin: auto; } img { width: 100%; } .portfolioContainer { margin: 8px -16px; } .portfolioContainer, .portfolioContainer > .ImageCol { padding: 8px; } .ImageCol { float: left; width: 25%; } .portfolioContainer:after { content: ""; display: table; clear: both; } .portfolioContent { background-color: white; padding: 10px; } @media screen and (max-width: 900px) { .ImageCol { width: 50%; } } @media screen and (max-width: 600px) { .ImageCol { width: 100%; } } </style> </head> <body> <main> <h1>Photography</h1> <hr /> <div class="portfolioContainer"> <div class="ImageCol"> <div class="portfolioContent"> <img src="https://i.picsum.photos/id/531/400/400.jpg" /> <h3>Picture 1</h3> <p>Clicked at my house</p> </div> </div> <div class="ImageCol"> <div class="portfolioContent"> <img src="https://i.picsum.photos/id/511/400/400.jpg" /> <h3>Picture 2</h3> <p>Clicked at Tenesse</p> </div> </div> <div class="ImageCol"> <div class="portfolioContent"> <img src="https://i.picsum.photos/id/521/400/400.jpg" /> <h3>Picture 3</h3> <p>Clicked on a bridge while travelling</p> </div> </div> <div class="ImageCol"> <div class="portfolioContent"> <img src="https://i.picsum.photos/id/551/400/400.jpg" /> <h3>Picture 4</h3> <p>Riding my safari jeep in sahara</p> </div> </div> </div> </main> </body> </html>
โครงสร้าง
- main { max-width: 1000px; margin: auto; } - จำกัดความกว้างสูงสุด จัดกึ่งกลาง
- .portfolioContainer { margin: 8px -16px; } - Negative Margin ชดเชย Padding Item
- .ImageCol { float: left; width: 25%; padding: 8px; } - 4 คอลัมน์
- .portfolioContent { background: white; padding: 10px; } - การ์ดสีขาว ขอบใน
- Clearfix: .portfolioContainer:after { clear: both; } - ล้าง Float
Responsive Breakpoints
- >= 900px: 4 คอลัมน์ (25%)
- 600-900px: 2 คอลัมน์ (50%)
- < 600px: 1 คอลัมน์ (100%)
CSS Grid Version (แนะนำ)
.portfolioContainer {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 16px;
}
หนึ่งบรรทัด แทน Float + Media Query + Clearfix
ผลลัพธ์
กริด 4 รูป (บน Desktop) พร้อม Caption และ Description การ์ดสีขาวบนพื้นเทา