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

จัดตำแหน่ง HTML5 SVG ให้อยู่กึ่งกลางหน้าจอ

ใช้ CSS Margin Auto + Display Block

HTML

<svg id="svgelem" height="200" xmlns="https://www.w3.org/2000/svg">
  <circle id="redcircle" cx="50" cy="50" r="50" fill="red" />
</svg>

CSS

#svgelem {
    display: block;
    margin-left: auto;
    margin-right: auto;
    /* หรือ */
    /* margin: 0 auto; */
}

ทางเลือก: Flexbox บน Parent

body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
}

SVG เป็น Inline Element โดย Default ต้องตั้ง display: block หรือ inline-block ก่อนจึง margin: auto ได้