CSS Basic Learning--8 Box Model (Box Model)

1. Introduction

        All HTML elements can be viewed as boxes. In CSS, the term "box model" is used for design and layout.

The CSS Box Model is essentially a box that encapsulates surrounding HTML elements, it includes: margins, borders, padding, and actual content.

        The box model allows us to place elements in the space between other elements and the borders of surrounding elements.

        The picture below illustrates the Box Model:

Explanation of the different sections:

  • Margin  - Clears the area outside the border, the margin is transparent.
  • Border  - A border around the padding and outside the content.
  • Padding  - Clears the area around the content, the padding is transparent.
  • Content  - The content of the box, displaying text and images.

2. The width and height of the element

        Important:  When you specify the width and height properties of a CSS element, you are only setting the width and height of the content area. Be aware that for full sized elements, you also have to add padding, borders and margins.

The elements in the example below have a total width of 450px:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>CSS基础学习</title>
<style>
div {
    background-color: lightgrey;
    width: 300px;
    border: 25px solid green;
    padding: 25px;
    margin: 25px;
}
</style>
</head>
<body>

<h2>盒子模型演示</h2>

<p>CSS盒模型本质上是一个盒子,封装周围的HTML元素,它包括:边距,边框,填充,和实际内容。</p>

<div>这里是盒子内的实际内容。有 25px 内间距,25px 外间距、25px 绿色边框。</div>

</body>
</html>

Renderings:

 Let's do the math:
300px (width)
+ 50px (left + right padding)
+ 50px (left + right border)
+ 50px (left + right margin)
= 450px

The formula for calculating the total width of the final element is as follows :

Total element width = width + left padding + right padding + left border + right border + left margin + right margin

The final calculation formula of the total height of the element is as follows:

The height of the total element = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin

Guess you like

Origin blog.csdn.net/yyxhzdm/article/details/131178320