CSS Box Model
All HTML elements can be regarded as boxes. In CSS, the term "box model" is used in design and layout.
The CSS box model is essentially a box that encapsulates surrounding HTML elements, including: margins, borders, padding, and the actual content.
The box model allows us to place elements in the space between other elements and the surrounding element's border.
The following picture illustrates the Box Model:
Explanation of different parts:
Margin - clears the area outside the border and makes the margin transparent.
Border(border) - A border around padding and outside the content.
Padding(Padding) - Clears the area around the content and makes the padding transparent.
Content(content) - The content of the box, showing text and images.
In order to set the width and height of elements correctly in all browsers, you need to know how the box model works.
The width and height of the element
Note: When you specify a When using the width and height properties of a CSS element, you are just setting the width and height of the content area. Be aware that to fully size an element, you must also add padding, borders, and margins. .
The total width of the elements in the example below is 300px:
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
Let’s do the math ourselves:
250px (width)
+ 20px (left + right padding)
+ 10px ( left + right border)
+ 20px (left + right margin)
= 300px
Just imagine, you only have 250 pixels of space. Let’s set an element with a total width of 250 pixels:
Example
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <style> div.ex { width:220px; padding:10px; border:5px solid gray; margin:0px; } </style> </head> <body> <img src="https://img.php.cn/upload/course/000/000/006/58088c38d34b6935.jpg" width="250" height="250" /> <div class="ex">上面的图片是250 px宽。这个元素的总宽度也是250 px。.</div> </body> </html>
Run the program to try it out
The formula for calculating the total width of the final element is as follows: