About

CSS Box Model

Jun 10th, 2022

1 min read

CSS box model เป็น box ที่คลุมทุกๆ element ของ HTML ไว้ การจะสร้าง Layout ที่ดี ให้กับเว็บไซต์ เราจำเป็นต้องเข้าใจถึง CSS box model
CSS box model ประกอบด้วยส่วนต่างๆ ดังนี้

  1. content area : ส่วนที่แสดง text หรือ รูปภาพ
  2. padding : เป็นช่องว่างที่อยู่ภายใน border ซึ่งคั่นระหว่าง border กับ content ถัดไป
  3. border :  อยู่รอบ content area และ padding ถ้าสามารถเห็น border ได้ เราจะเห็นการแยกชัดเจนระหว่าง padding กับ margin
  4. margin : เป็นช่องว่างที่อยู่ภายนอก border ซึ่งคั่นระหว่าง border กับ element ถัดไป
ฺCSS Box Model

(image source)

Css Box Model

(image source)

จากภาพตัวอย่างข้างบน จะเห็นว่าเรากำหนดค่า width: 300px; ไว้
การกำหนด width ของ content-box จะหมายถึงความกว้างของ content area อย่างเดียว ส่วน border-box จะหมายถึงความกว้างภายใน border (content area + padding + border)

content-box
width = content-area
300 = 300

border-box
width = content area + padding + border
300 = 260 + (15x2) + (5x2)
300 = 260 + (padding ซ้ายและขวา) + (border ซ้ายและขวา)

Reference: What is the difference between border-box and content-box in CSS?


Related Posts