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

บทบาทของ margin: auto ในการจัดกึ่งกลางแนวนอน


จัดกึ่งกลางบล็อกด้วย margin: auto

กำหนด width ให้องค์ประกอบ แล้วใช้ margin: auto จะทำให้มันอยู่กึ่งกลางแนวนอนภายในพาเรนต์

ตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    div {
      width: 200px;
      margin: auto;
      border: 2px dashed blue;
    }
  </style>
</head>
<body>
  <p>This is demo text</p>
  <div>This is horizontally centered because it has margin: auto;</div>
</body>
</html>