align-items: flex-end คืออะไร?
ค่า flex-end ของ align-items จัดเรียง flex items ชิด จุดสิ้นสุดของ Cross Axis (จุดท้ายของแกนตั้งฉาก)
พฤติกรรมตาม flex-direction
| flex-direction | Main Axis | Cross Axis | flex-end หมายถึง |
|---|---|---|---|
| row (default) | แนวนอน (ซ้าย→ขวา) | แนวตั้ง (บน→ล่าง) | ชิดล่าง (Bottom) |
| row-reverse | แนวนอน (ขวา→ซ้าย) | แนวตั้ง (บน→ล่าง) | ชิดล่าง (Bottom) |
| column | แนวตั้ง (บน→ล่าง) | แนวนอน (ซ้าย→ขวา) | ชิดขวา (Right) |
| column-reverse | แนวตั้ง (ล่าง→บน) | แนวนอน (ซ้าย→ขวา) | ชิดขวา (Right) |
ตัวอย่าง: flex-direction: row (default) → ชิดล่าง
<!DOCTYPE html>
<html>
<head>
<style>
.mycontainer {
display: flex;
height: 300px; /* ความสูงจำกัด */
background-color: #ffebee;
align-items: flex-end; /* จัดชิดล่าง (Cross Axis = Vertical) */
}
.mycontainer > div {
background-color: #ff5722;
color: white;
text-align: center;
line-height: 60px;
font-size: 24px;
width: 100px;
margin: 5px;
border-radius: 4px;
/* ไม่มี height -> จะสูงตาม content (60px) แล้วจัดชิดล่าง */
}
</style>
</head>
<body>
<h1>ตัวอย่าง align-items: flex-end (row direction)</h1>
<p>Items จัดชิดด้านล่างของ container (ความสูง 300px)</p>
<div class="mycontainer">
<div>Q1</div>
<div>Q2</div>
<div>Q3</div>
<div>Q4</div>
</div>
</body>
</html>
ตัวอย่าง: flex-direction: column → ชิดขวา
.column-end {
display: flex;
flex-direction: column;
width: 400px; /* ความกว้างจำกัด */
align-items: flex-end; /* จัดชิดขวา (Cross Axis = Horizontal) */
gap: 10px;
padding: 10px;
background: #f5f5f5;
}
.column-end > div {
background: #2196f3;
color: white;
padding: 10px 20px;
border-radius: 4px;
/* width: auto -> กว้างตาม content แล้วจัดชิดขวา */
}
การใช้งานจริง: Chat Bubbles (ฝั่งตัวเอง)
.chat-container {
display: flex;
flex-direction: column;
gap: 12px;
padding: 16px;
max-width: 400px;
}
.message {
display: flex;
max-width: 80%;
}
.message.own {
align-self: flex-end; /* ข้อความตัวเองชิดขวา */
/* หรือใช้ container: align-items: flex-end */
}
.message.own .bubble {
background: #007bff;
color: white;
border-radius: 18px 18px 0 18px;
}
.message.other {
align-self: flex-start; /* ข้อความคนอื่นชิดซ้าย */
}
.message.other .bubble {
background: #f1f1f1;
color: #333;
border-radius: 18px 18px 18px 0;
}
การใช้งานจริง: Form với Label + Input
.form-row {
display: flex;
align-items: flex-end; /* Label และ Input ชิดล่างเท่ากัน */
gap: 16px;
}
.form-row label {
font-weight: 500;
margin-bottom: 4px;
}
.form-row input {
flex: 1;
padding: 10px;
}
คำแนะนำ
- ใช้
flex-endเมื่อต้องการจัดชิด "ท้าย" ของ Cross Axis - จำไว้: Cross Axis ขึ้นอยู่กับ
flex-direction(row=vertical, column=horizontal) - ร่วมกับ
justify-content: flex-endได้ "ชิดมุมขวาล่าง" (สำหรับ row) - สำหรับ item เดียว ให้ใช้
align-self: flex-endแทน