การสร้างเว็บไซต์ Responsive ที่ทำงานได้ดีบน PC, Laptop, Tablet และ Phone ต้องใช้หลักการ Mobile-First ร่วมกับ Media Queries และหน่วยวัดที่ยืดหยุ่น (Relative Units) ตัวอย่างด้านล่างเป็น Layout เต็มรูปแบบพร้อม Header, Navigation, Main Content และ Footer
ตัวอย่างโค้ด
<!DOCTYPE html>
<html lang="en">
<head>
<title>Page Title</title>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
* { box-sizing: border-box; }
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; margin: 0; }
.header {
padding: 80px;
text-align: center;
background: #7b1abc;
color: white;
}
.header h1 { font-size: 40px; }
nav {
width: 100%;
background-color: rgb(39, 39, 39);
overflow: auto;
height: auto;
}
.links {
display: inline-block;
text-align: center;
padding: 14px;
color: rgb(178, 137, 253);
text-decoration: none;
font-size: 17px;
}
.links:hover { background-color: rgb(100, 100, 100); }
.selected { background-color: rgb(0, 18, 43); }
main { background-color: white; padding: 20px; }
.footer {
padding: 20px;
text-align: center;
color: white;
background: rgb(255, 0, 0);
}
</style>
</head>
<body>
<div class="header"><h1>Website ↶</h1></div>
<nav>
<a class="links selected" href="#"> Home</a>
<a class="links" href="#"> Login</a>
<a class="links" href="#"> Register</a>
<a class="links" href="#"> Contact Us</a>
<a class="links" href="#"> More Info</a>
</nav>
<main>
<h2>Sample Heading</h2>
<h5>Published in January</h5>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Eum, autem.</p>
<br />
<h2>Sample Heading</h2>
<h5>Published in march</h5>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Unde quo minus fugiat tempora quae ratione dignissimos exercitationem voluptate officiis reiciendis.</p>
</main>
<div class="footer"><h2>Footer ↷</h2></div>
</body>
</html>
องค์ประกอบหลักของ Responsive Design
- Viewport Meta Tag -
<meta name="viewport" content="width=device-width, initial-scale=1">บังคับให้เบราว์เซอร์มือถือแสดงในขนาดจริง - Box-sizing: border-box - ทำให้ padding และ border รวมอยู่ใน width/height
- Flexible Images - ใช้
max-width: 100%; height: auto;ให้รูปภาพย่อตามคอนเทนเนอร์ - Media Queries - ปรับ Layout ตาม Breakpoints ต่างๆ
Navigation Bar ที่ Responsive
ในตัวอย่างใช้ display: inline-block สำหรับลิงก์เมนู ซึ่งจะต่อเนื่องกันแนวนอนบนเดสก์ท็อป สำหรับมือถือควรเพิ่ม Media Query เพื่อเปลี่ยนเป็น display: block หรือใช้ Hamburger Menu
แนวทางปรับปรุงสำหรับ Production
- เพิ่ม Media Queries สำหรับ Tablet (768px) และ Mobile (480px)
- ใช้ CSS Grid/Flexbox สำหรับ Layout หลักแทน float
- เพิ่ม Hamburger Menu ด้วย JavaScript สำหรับมือถือ
- ใช้หน่วย
remหรือemแทน px สำหรับ Typography - เพิ่ม
min-height: 100vhให้ main เพื่อให้ Footer อยู่ล่างสุดเสมอ