flex คืออะไร?
คุณสมบัติ flex เป็น shorthand property ที่รวม 3 คุณสมบัติของ flex item ไว้ในบรรทัดเดียว:
- flex-grow - อัตราส่วนการขยาย
- flex-shrink - อัตราส่วนการบีบ
- flex-basis - ขนาดเริ่มต้นก่อน grow/shrink
ไวยากรณ์
flex: ;
ตัวอย่าง: flex: 20 0 350px
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
background-color: #fff3e0;
padding: 10px;
gap: 10px;
}
.mycontainer > div {
background-color: white;
border: 2px solid #ff9800;
text-align: center;
line-height: 40px;
font-size: 20px;
width: 100px;
margin: 5px;
border-radius: 4px;
}
</style>
</head>
<body>
<h1>ตัวอย่าง flex shorthand: Q4 ใช้ flex: 20 0 350px</h1>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div style="flex: 20 0 350px">Q4 (grow:20, shrink:0, basis:350px)</div>
<div>Q5</div>
<div>Q6</div>
<div>Q7</div>
<div>Q8</div>
<div>Q9</div>
</div>
</body>
</html>
รูปแบบย่อที่นิยมใช้ (Common Patterns)
| Shorthand | เทียบเท่า | คำอธิบาย |
|---|---|---|
flex: 1 |
1 1 0% |
ขยายเท่ากัน, บีบได้, เริ่มจาก 0 (Equal columns) |
flex: 2 |
2 1 0% |
ขยาย 2 เท่าของ flex: 1 |
flex: auto |
1 1 auto |
ขยาย/บีบตาม content size (default behavior) |
flex: initial |
0 1 auto |
ไม่ขยาย, บีบได้, basis = auto (ค่าเริ่มต้น) |
flex: none |
0 0 auto |
ไม่ขยาย, ไม่บีบ, ขนาดคงที่ตาม content |
flex: 0 0 200px |
0 0 200px |
ขนาดคงที่ 200px (ไม่ขยาย ไม่บีบ) |
flex: 1 0 300px |
1 0 300px |
ขยายได้ แต่ไม่บีบ, เริ่มต้น 300px |
ตัวอย่างปฏิบัติ: Layout Patterns
1. Equal Width Columns (คอลัมน์เท่าๆ กัน)
.equal-cols {
display: flex;
}
.equal-cols > * {
flex: 1; /* 1 1 0% - แบ่งพื้นที่เท่ากัน */
}
2. Fixed Sidebar + Fluid Content
.layout {
display: flex;
}
.sidebar {
flex: 0 0 280px; /* คงที่ 280px */
}
.content {
flex: 1; /* ขยายเต็มพื้นที่เหลือ */
min-width: 0; /* ป้องกัน overflow */
}
3. Sticky Footer Pattern
.page {
display: flex;
flex-direction: column;
min-height: 100vh;
}
.header { flex: 0 0 auto; }
.main { flex: 1 0 auto; } /* ขยายเต็มพื้นที่กลาง */
.footer { flex: 0 0 auto; }
4. Media Object (Image + Text)
.media {
display: flex;
gap: 16px;
align-items: flex-start;
}
.media-img {
flex: 0 0 120px; /* รูปคงที่ */
}
.media-body {
flex: 1; /* ข้อความขยายเต็ม */
min-width: 0;
}
คำแนะนำ
- ใช้ shorthand
flexแทนการเขียน 3 คุณสมบัติแยกกัน (สั้นกว่า และ browser optimize ได้ดีกว่า) flex: 1คือ pattern ที่ใช้บ่อยที่สุดสำหรับ equal columns- จำไว้:
flex-basis: 0(ใน flex: 1) ทำให้แบ่งพื้นที่เท่ากัน "จริงๆ" ไม่คำนึง content width - ใช้
flex: 0 0 auto(หรือflex: none) สำหรับ items ที่ต้องการขนาดคงที่ - ใส่
min-width: 0บน flex items ที่มี text overflow หรือ nested flex