When we lay out a web page, we often encounter a situation where the width or height of the final web page will exceed our pre-calculation. This is actually caused by the so-called CSS box model.
| #test{margin:10px;padding:10px;width:100px;height:100px;} |
As in the code above, many times we will calculate the position it occupies as width: 120px, height: 120px, because under normal understanding, padding is the inner margin, which should be included in the width, and margin is the outer edge. distance, so width=margin-left + margin-right + width, but the browser’s interpretation of the CSS box model is not the same, so in the end we will find that the width and height of the laid out web page will exceed our expected calculations, and finally cause the display misalignment.
In fact, it is not the case. The real calculation of the position occupied by test should be width=margin-left + margin-right + padding-left + padding-right + width, that is, the real size of the width should be inner margin + outer margin. +The width itself, that is to say, the real size of test should be 140px. The calculation of height is the same as the calculation of width.
And if a border is added to the test, the width and height algorithm should also add the size of the border.
| #test{margin:10px;padding:10px;border:5px;width:100px;height:100px;} |
The width of the test here should be the outer border + inner border + border + width itself, so the width of the test is 150px.
As shown in the figure below, the actual position occupied by width and height is not the small area itself, but should go all the way to the outermost dark blue layer.