Media Queries เป็นหัวใจของ Responsive Design ช่วยให้เราใช้ CSS ต่างกันได้ตามขนาดหน้าจอ ตัวอย่างนี้แสดง Breakpoints มาตรฐานที่ใช้กันทั่วไป: Mobile (<600px), Tablet (600-768px), Desktop (768-992px), Large Desktop (992-1200px), และ Extra Large (>1200px)
ตัวอย่างโค้ด
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
color: white;
}
@media only screen and (max-width: 600px) {
body { background: rgb(207, 60, 151); }
}
@media only screen and (min-width: 600px) {
body { background: rgb(0, 128, 107); }
}
@media only screen and (min-width: 768px) {
body { background: rgb(226, 136, 18); }
}
@media only screen and (min-width: 992px) {
body { background: rgb(108, 25, 185); }
}
@media only screen and (min-width: 1200px) {
body { background: rgb(13, 124, 63); }
}
</style>
</head>
<body>
<h1>Typical Breakpoints Example</h1>
<h2> Resize the screen to see background color change on different breakpoints </h2>
</body>
</html>
Breakpoints มาตรฐาน (Common Breakpoints)
| อุปกรณ์ | ขนาดหน้าจอ | Media Query |
|---|---|---|
| Mobile (Portrait) | ≤ 600px | @media (max-width: 600px) |
| Mobile (Landscape) / Small Tablet | 600px - 768px | @media (min-width: 600px) |
| Tablet (Portrait) | 768px - 992px | @media (min-width: 768px) |
| Laptop / Small Desktop | 992px - 1200px | @media (min-width: 992px) |
| Large Desktop | ≥ 1200px | @media (min-width: 1200px) |
แนวทางเขียน Media Queries
1. Mobile-First (แนะนำ)
/* Base styles for mobile */
body { font-size: 16px; }
/* Tablet and up */
@media (min-width: 768px) {
body { font-size: 18px; }
}
/* Desktop and up */
@media (min-width: 1024px) {
body { font-size: 20px; }
}
2. Desktop-First
/* Base styles for desktop */
body { font-size: 20px; }
/* Tablet and down */
@media (max-width: 1024px) {
body { font-size: 18px; }
}
/* Mobile and down */
@media (max-width: 768px) {
body { font-size: 16px; }
}
Best Practices
- ใช้ Mobile-First เพราะโค้ดน้อยกว่า และประสิทธิภาพดีกว่าบนมือถือ
- ใช้
min-widthมากกว่าmax-widthเพื่อหลีกเลี่ยงการ Override ซ้ำซ้อน - กำหนด Breakpoints ตามเนื้อหา (Content-based) ไม่ใช่ตามอุปกรณ์เฉพาะ
- รวม Media Queries ที่เกี่ยวข้องไว้ด้วยกันในไฟล์ CSS
- ทดสอบบนอุปกรณ์จริงและ Developer Tools ของเบราว์เซอร์
CSS Custom Properties (Variables) กับ Media Queries
:root {
--container-width: 100%;
--font-size: 16px;
}
@media (min-width: 768px) {
:root {
--container-width: 720px;
--font-size: 18px;
}
}
.container { width: var(--container-width); }
body { font-size: var(--font-size); }