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

วิธีจัดตำแหน่ง Div ให้อยู่กึ่งกลางด้วย CSS

ภาพรวม

มีหลายวิธีจัด <div> ให้อยู่กึ่งกลางแนวนอน (Horizontal Centering) และ/หรือแนวตั้ง (Vertical Centering) ใน CSS

วิธีที่ 1: Margin Auto (Horizontal Only) - Classic


/* CSS */
.center-div {
    width: 50%;           /* ต้องมี Width */
    margin: 0 auto;       /* Top/Bottom 0, Left/Right Auto */
    border: 2px solid blue;
}

<div class="center-div">This paragraph is in center</div>

วิธีที่ 2: Flexbox (Modern - Horizontal + Vertical)


/* Parent Container */
.container {
    display: flex;
    justify-content: center; /* Horizontal Center */
    align-items: center;     /* Vertical Center */
    height: 100vh;           /* ต้องมี Height */
}

/* หรือแค่แนวนอน */
.container-h {
    display: flex;
    justify-content: center;
}

<div class="container">
    <div class="center-div">Centered Both Directions</div>
</div>

วิธีที่ 3: Grid (Modern - Simple)


.container {
    display: grid;
    place-items: center;     /* Horizontal + Vertical Center */
    height: 100vh;
}

วิธีที่ 4: Absolute Transform (Fixed Width/Height)


.center-div {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 300px;
    height: 200px;
}

วิธีที่ 5: Text Align (สำหรับ Inline/Inline-block Content)


.container {
    text-align: center;
}
.center-div {
    display: inline-block;
    text-align: left; /* Reset text align ภายใน */
}

วิธีที่ 6: HTML Align Attribute (Legacy - ไม่แนะนำ)


<div align="center">This paragraph is in center</div>

❌ Deprecated ใน HTML5 ควรใช้ CSS แทน

ตารางเปรียบเทียบ

วิธีแนวนอนแนวตั้งBrowser SupportComplexity
Margin Auto✅❌AllLow
Flexbox✅✅IE10+Low
Grid✅✅ModernLowest
Absolute + Transform✅✅IE9+Medium
Text Align✅ (Inline)❌AllLow

แนะนำสำหรับโปรเจกต์ใหม่

  • Flexbox - รองรับดี กระชับ ใช้ได้หลากหลาย
  • Grid - โค้ดสั้นที่สุด (place-items: center) สำหรับ Modern Browser
  • Margin Auto - ใช้ได้ทุกที่ สำหรับ Horizontal Only

ตัวอย่างครบถ้วน


<!DOCTYPE html>
<html>
<head>
<style>
.container { display: flex; justify-content: center; align-items: center; height: 100vh; background: #f0f0f0; }
.box { width: 300px; padding: 20px; background: white; border: 4px solid #333; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
.box h2 { margin-top: 0; text-align: center; }
</style>
</head>
<body>
    <div class="container">
        <div class="box">
            <h2>Perfectly Centered</h2>
            <p>This div is centered both horizontally and vertically using Flexbox.</p>
        </div>
    </div>
</body>
</html>