All HTML elements can be considered as boxes. In CSS, the term "box model" is used when talking about design and layout.
The CSS box model is essentially a box that wraps around HTML elements, and it consists of: margins, borders, padding, and the actual content.网页元素可以理解为一个盒子,里面装这个各种元素:margin外边距(透明的),border边框(可视的)、padding内边距(可视的)、实际的页面内容。可以说,网页面里添加元素,会影响其他元素在网页上的位置,好比一个盒子里放东西,空间会被占,产生挤压效果,导致一些元素位置发生相对变化
The box model allows us to place a border around elements and space elements in relation to other elements.
各种HTML元素含义:
- Margin - Clears an area around the border. The margin does not have a background color, it is completely transparent
- 清空边框周围的区域,它是透明的,好比边框的一层保护层,隔绝其他元素靠近
- Border - A border that goes around the padding and content. The border is inherited 继承from the color property of the box
- 边框是围绕在内层保护膜padding和实际内容content周围的一个边界线,可以和其他元素划分出各自边界
- Padding - Clears an area around the content. The padding is affected by the background color of the box
- 清空实际内容周围的区域,它可以有有色,受整个box颜色影响
- Content - The content of the box, where text and images appear
- box的内容,用来展示图片和字符
页面元素在不同的浏览器中所展现的宽度和高度会有所不同
Important:
When you set the width and height properties of an element with CSS, you just set the width and height of the
content area
. To calculate the full size of an element, you must also add the padding, borders and margins.
当你设置一个元素的宽度和高度,你只是设置了这个content区域的宽高,要计算整个元素的size,要加上内边距,边框和外边距才是完整的元素大小
一个计算一个元素完整宽度的例子:
css样式:实际元素width为300像素点
width:250px;
padding:10px;
border:5px solid gray;
margin:10px;
padding:10px;
border:5px solid gray;
margin:10px;
Let's do the math:
250px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 20px (left + right margin)
= 300px
250px (width)
+ 20px (left + right padding)
+ 10px (left + right border)
+ 20px (left + right margin)
= 300px
IE8或更早的IE版本中,width属性包含了padding和border的大小在内,为解决统一显示:需加 <!DOCTYPE html>声明