May 30, 2021 Article blog
The following code can be copied directly out to run Oh
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>css盒模型</title>
</head>
<style type="text/css">
.content {
width: 300px;
height: 400px;
border: 5px solid #242424;
padding: 20px;
background-color: #898989;
}
</style>
<body>
<div class="content" id="zwkkkk1"></div>
</body>
</html>
The logic of the code above is simple: set a div that is 300px wide, 400px high, and set a 5px border and a 20px padding.
Then let's look at the effect:
Here we will find that we have set a 300 x 400 aspect ratio, why present a box of 350 x 450? Next let's open the debug page to find out exactly.
We can find this diagram below:
In this image, we find that the
300*400
we set appears in the innermost blue box, and
border
at the same time we can find that in this box model there are
margin
borders,
padding
(inner borders) in addition to what we set
content
margin(外边距)
the area outside the border, which is transparent.
border(边框)
that surrounds outside the margins and content.
padding(内边距)
- Clears the area around the content, and the margin is transparent.
content(内容)
contents of the box, displaying text and images.
In order to correctly set the width and height of elements in all browsers, you need to know how the box model works.
And the
350*450
box we saw in the test results diagram,
350(width) = 300(content) + 20(padding)* 2 + 5(border)* 2
450(height) = 400 (content)+ 20(padding)* 2 + 5(border)* 2
The reason for the above effect comes from the difference between the two box models of css, and here I'll introduce the two box models first.
In a standard box model, width refers to the width of the content section
In the IE box model, width represents the width of the three parts, content and padding
We can see that the default we use above is the W3C standard box model
And here the choice of box model is more inclined to projects and developer habits, there is no absolute good or bad.
If you want to switch the box model is also simple, you need to rely on the
box-sizing
property of CSS3
box-sizing:
content-box
is the W3C box model
box-sizing:border-box
is the IE box model
The default property of box-sizing is content-box