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

Responsive Web Design ด้วย Media Queries ใน CSS

Media Queries: ใช้สไตล์ต่างกันตามขนาดอุปกรณ์

Media Queries ใช้ @media rule กรองเงื่อนไข (width, height, orientation, resolution) ใส่ CSS เฉพาะที่ตรงเงื่อนไข สร้าง Responsive Design

โค้ดตัวอย่าง: เปลี่ยนสีพื้นหลังตาม Breakpoint

<!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>ตัวอย่าง Media Queries</h1>
  <h2>Resize หน้าจอเพื่อดูสีพื้นหลังเปลี่ยน</h2>
</body>
</html>

Media Query Syntax

@media mediatype and (feature: value) { CSS rules }
@media screen and (max-width: 768px) { ... }
@media (min-width: 600px) and (max-width: 900px) { ... } /* Range */
@media (orientation: portrait) { ... }

Common Features

  • width, height, min-width, max-width, min-height, max-height
  • orientation: portrait | landscape
  • resolution (dpi, dpcm, dppx) – สำหรับ Retina/High-DPI
  • hover, pointer – ตรวจจับ input capability
  • prefers-color-scheme, prefers-reduced-motion – User preferences

แนวทางปัจจุบัน: Mobile First + CSS Variables

:root { --bg: #fff; --text: #000; }
@media (prefers-color-scheme: dark) {
  :root { --bg: #000; --text: #fff; }
}
@media (min-width: 768px) {
  :root { --container-max: 720px; }
}

รวม Media Queries เข้ากับ Design System ผ่าน CSS Variables จะจัดการง่ายและ consistent