Automatically translated.View original post

css box model

# Web Site Writing Basics

The CSS Box Model is a format that describes how to manage and place HTML elements in a web page. Each element is seen as a rectangular box with components: Content, Padding, Border, and Margin.

Components of the CSS Box Model:

Contents:

A section that shows the actual content of an element, such as text, images, or video.

Paddling:

The empty space between the content and the edges of the elements.

Border:

Border surrounding content and spacing (padding).

Margin:

The empty space outside the edge of an element determines the distance between it and other elements.

Box Model Operation:

The browser uses the CSS Box Model to calculate the size and position of each element on a web page. Understanding the Box Model allows us to accurately control the placement and size of the elements. Setting features such as width (width), height (height), spacing (padding), edges (border) and margins (margin) will affect the size and shape of the box.

Benefits of Box Model:

Element placement:

Box Model allows us to control the precise placement of elements on web pages.

Size Designation:

We can freely determine the size of the elements (width, height) and the free space around the content (padding, margin).

Creating a complex layout:

With the Box Model, we can create complex and beautiful layouts.

Example:

Suppose we have a div element with text content, and we want to have a distance around the text and a border, we can use the Box Model to configure the following:

Code

. My-element {

width: 200px; / * Define content width * /

Height: 100px; / * Determine content height * /

Padding: 20px; / * Define the spacing around 20px content * /

Border: 2x solid black; / * Define 2px thick black border * /

Margin: 10px; / * Define 10px margin * /

}

Based on this example, the box of .my-element will contain content (text), spacing (padding) 20px, edge (border) 2px, and margin (margin) 10px.

2025/8/19 Edited to

... Read moreเมื่อเข้าใจส่วนประกอบหลักของ CSS Box Model แล้ว การปรับใช้แต่ละส่วนเพื่อตอบโจทย์การจัดตำแหน่งบนหน้าเว็บจะช่วยพัฒนาเลย์เอาต์ให้มีความสวยงามและใช้งานได้ดีขึ้น ในประสบการณ์ส่วนตัว ผมมักใช้ Margin เพื่อเว้นระยะห่างระหว่างกล่องแต่ละองค์ประกอบให้เหมาะสม ลดความแน่นของหน้าจอ และใช้ Padding เพื่อเพิ่มพื้นที่ว่างภายในกล่อง ช่วยให้เนื้อหาไม่ติดขอบเกินไป ทำให้อ่านง่ายและดูเป็นระเบียบ นอกจากนี้ Border ก็เป็นตัวช่วยเน้นกรอบขององค์ประกอบแต่ต้องระวังขนาดของเส้นขอบไม่ควรหนาหรือบางเกินไปเพราะส่งผลกระทบกับขนาดกล่องโดยรวม และถ้าต้องการจัดตำแหน่งองค์ประกอบแบบละเอียด การใช้ค่า width, height ควบคู่กับ box-sizing จะช่วยให้กำหนดขนาดรวมขอบและระยะขอบได้ตรงตามที่ออกแบบไว้ อย่าลืมว่าการใช้ Box Model ร่วมกับเทคนิคการจัดตำแหน่งอื่นๆ เช่น flexbox หรือ grid จะช่วยเพิ่มความยืดหยุ่นและสร้างเลย์เอาต์ที่ซับซ้อนและตอบโจทย์ความต้องการใช้งานได้อย่างดีแบบครบวงจรมากขึ้น