ในการแบ่งพื้นที่หน้าจอออกเป็นสามส่วนได้ตามที่ต้องการ โดยใช้ Flexbox เพื่อจัดการเลย์เอาต์ และกำหนดความสูงของแต่ละส่วนได้ดังนี้:
5. ใช้
1. เพิ่มโค้ดใน <style> ... </style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
flex-direction: column;
height: 100vh; /* ใช้ความสูงเต็มจอ */
}
header {
height: 80px;
width: 100%;
background-color: #4CAF50; /* สีพื้นหลังตัวอย่าง */
text-align: center;
line-height: 80px; /* จัดข้อความให้อยู่กลางแนวตั้ง */
color: white;
font-size: 20px;
}
main {
flex: 1; /* ให้ส่วนนี้ขยายตัวตามพื้นที่ว่าง */
width: 100%;
background-color: #f0f0f0; /* สีพื้นหลังตัวอย่าง */
text-align: center;
padding: 20px;
}
footer {
height: 80px;
width: 100%;
background-color: #333; /* สีพื้นหลังตัวอย่าง */
text-align: center;
line-height: 80px; /* จัดข้อความให้อยู่กลางแนวตั้ง */
color: white;
font-size: 18px;
}
2. เพิ่มโค้ดใน <body> ... </body>
<header>
ส่วนหัว (Header)
</header>
<main>
ส่วนเนื้อหา (Content)
</main>
<footer>
ส่วนท้าย (Footer)
</footer>
ตัวอย่างการใช้งาน
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>แบ่งพื้นที่หน้าจอ</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
flex-direction: column;
height: 100vh; /* ใช้ความสูงเต็มจอ */
}
header {
height: 80px;
width: 100%;
background-color: #4CAF50; /* สีพื้นหลังตัวอย่าง */
text-align: center;
line-height: 80px; /* จัดข้อความให้อยู่กลางแนวตั้ง */
color: white;
font-size: 20px;
}
main {
flex: 1; /* ให้ส่วนนี้ขยายตัวตามพื้นที่ว่าง */
width: 100%;
background-color: #f0f0f0; /* สีพื้นหลังตัวอย่าง */
text-align: center;
padding: 20px;
}
footer {
height: 80px;
width: 100%;
background-color: #333; /* สีพื้นหลังตัวอย่าง */
text-align: center;
line-height: 80px; /* จัดข้อความให้อยู่กลางแนวตั้ง */
color: white;
font-size: 18px;
}
</style>
</head>
<body>
<header>
ส่วนหัว (Header)
</header>
<main>
ส่วนเนื้อหา (Content)
</main>
<footer>
ส่วนท้าย (Footer)
</footer>
</body>
</html>
คำอธิบาย:
1. header
: กำหนดความสูง 80 พิกเซล และกว้าง 100% อยู่ขอบบนของจอ2. main
: ใช้ flex: 1
เพื่อให้ขยายพื้นที่อัตโนมัติตามที่เหลืออยู่3. footer
: กำหนดความสูง 80 พิกเซล และกว้าง 100% อยู่ขอบล่างของจอ4. body
: ใช้ display: flex
และ flex-direction: column
เพื่อจัดเรียงส่วนต่าง ๆ ในแนวตั้ง5. ใช้
height: 100vh
เพื่อให้หน้าจอทั้งหมดใช้ความสูงเต็ม 100% ของ viewportนำโค้ดนี้ไปปรับใช้ได้เลย!