`
zha_zi
  • 浏览: 590286 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

CSS Box Model

    博客分类:
  • css
 
阅读更多

The CSS Box Model

 

Your understanding of the box model concept, and how it relates to the way in which an element’s final dimensions are determined, will be essential to your understanding of how an element is positioned on a web page. The box model applies to block-level elements. A companion concept, the inline layout model, defines how inline elements are positioned, and is covered in Inline Formatting.

Calculating Box Dimensions

In CSS2.1, block-level elements can only be rectangular. We calculate the overall dimensions of a block-level element by taking into account the height and width of the content area, as well as any margins, padding, and borders that are applied to the element.

We can define the content width of an element by declaring its width and heightproperties. If no declarations are applied, the default value for the width and heightproperties is auto.

For static (non-positioned) elements, and relatively positioned elements where thewidth property has the value auto, the computed width will be the width of the containing block minus any horizontal margins, borders, padding, and scrollbars. That is, it will be whatever’s left over when horizontal margins, borders, padding, and scrollbars (if any) have been deducted from the width of the containing block.

The containing block is the reference rectangle whose position and dimensions are used for relative calculations of descendant elements’ positions and dimensions. Although elements are positioned with respect to their containing block, they’re not confined by it, and they may overflow. In most cases, generated boxes act as containing blocks for descendant boxes. The full details of containing blocks are covered in Containing Block.

For floated or absolutely positioned elements (including elements for which positionis set to fixed), a width of auto will make the generated box shrink to the intrinsic dimensions of its contents.

Note:Floated Elements and Width

Previously, in CSS2, floated elements without a declared width value would not shrink to wrap their content; instead, they’d expand to the full width of their parent element. This behavior was changed in CSS2.1 to allow the shrink-wrapping to take place. However, in Internet Explorer 6 and earlier versions, a floated element with no declared width value will shrink to wrap its content as per the specifications unless a child element has a layout, in which case the floated parent will expand to fill the available content width of the parent.1

It should also be noted that when a float (without a declared width) contains a right-floated child element, it will also expand to fill the parent’s available content width in IE browsers up to and including version 7 (Firefox up to and including version 2.0 also exhibits this bug but, the problem appears to have been fixed as of Firefox 3.0 Alpha 6).

Therefore, it’s always safer to specify an explicit value for the width of a floated element where possible, and thereby to avoid the buggy behavior described above. However, as long as you’re aware of the problems mentioned above, you’ll likely find that widthless floats can be useful in certain situations, such as fluid-width horizontal menus.

No matter how the content area is positioned, its height value will be equal to the content height if no values have been declared for height, or for min-height and max-height.

Therefore, to ascertain the total space required to place an element on the page, add the content area’s dimensions to any padding, borders, and margins that have been declared. Of course, an element may have no padding, border, or margins, in which case its dimensions will be dictated solely by its content.

If an element contains only floated or absolutely positioned elements, it will have no content at all, and its height will be zero. We’ll discuss this more in Floating and Clearing.

Implementing the Box Model

The box model is best demonstrated with a short example. The calculation we’ll use to ascertain the total space required to accommodate an element on the page (ignoring margin collapse for the time being—see below for more on this) will be as follows:

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

Total height = top margin + top border + top padding + height +
                   bottom padding + bottom border + bottom margin

Here’s our example CSS—a rule set that contains declarations for all the box properties of an element that has the class "box":

.box {
  width: 300px;
  height: 200px;
  padding: 10px;
  border: 1px solid #000;
  margin: 15px;
}

The total size of the element above will be calculated as follows:

Total width = 15 + 1 + 10 + 300 + 10 + 1 + 15 = 352px
Total height = 15 + 1 + 10 + 200 + 10 + 1 + 15 = 252px

The above calculation is depicted in Figure 1, which is taken from the element layout display from Firebug, the JavaScript and CSS development add-on for Firefox.

Figure 1. The CSS box model in actionA diagram displaying the width of a box and how it is
          calculated in CSS. The interior dimensions are added to the padding,
          border and margin widths.

In Figure 1, we can clearly see the content area in the center, the padding around the content area, the border area, and the margin area. The outer edge of the content area is called the content edge or inner edge; the outer edge of the padding area is called the padding edge; the outer edge of the border area is called the border edge; and the outer edge of the margin area is called—you guessed it—the margin edge or outer edge.

You can see from this short example that, for this element to fit on the page, we’ll need a space that’s at least 352px wide and 252px high. If the space available is any smaller than this, the element will be misplaced, or will overflow its containing block. Note that Internet Explorer 6 and earlier versions will most likely stretch the containing block to accommodate this extra height, and could severely disrupt the layout. Other browsers will let the element overflow its boundaries, but will ignore the content.

Note:Watch Out for Collapsing Margins

Although margins are included in the above calculations for the total space required to place the element, note that vertically adjacent margins on static (non-positioned) elements would collapse into the bigger margin of the elements that are adjacent above and below. This means that the actual space required to place an element would not necessarily extend from the margin edges of elements existing on the page: only the biggest margin will apply, and the smaller margins will appear to overlap the bigger margins. See Collapsing Margins for the full details of this quite complicated subject.

Practical Considerations of the Box Model

An important point to note is that an element that has its width set to 100% (that is, 100% of the content width of its parent element) shouldn’t have any margins, padding, or borders applied, as this would make it far too big for the space that it sits in. This is often overlooked by authors and can severely disrupt a page’s layout, as content will either overflow or push elements wider than they should be.

The solution, in most cases, is to avoid adding a value for the property width(other than auto), and to apply the margins, padding, and borders only. The widthproperty of a static element will default to auto, and even with padding, borders, and margins added, it will still assume the full available content width.

Of course, this approach may not be feasible in some instances, such as cases where the element is not a static element, and requires the definition of a specific width value (as in the case of a floated element that doesn’t automatically expand to fill its parent). In these cases, you have two options.

If the available space is of a fixed width, you can simply add the value of each component together to ensure that it matches the available width. For example, if the available space is 500px wide, and you require an element to have 20px padding, simply set the width to 460px and the padding to 20px for that element (20 + 460 + 20 = 500). This solution assumes that the length values specified for the element’s box properties use the same unit of measurement, since you won’t be able to add together a mixture of units (200px + 10%, for example, makes no sense in this context).

When the available content space has an unknown width—as in the case of a fluid layout—this method can’t be used, as percentages and pixels can’t be added together. In this case, the solution is to declare a width of 100% for the element concerned, and to apply the padding, border, and margin values to a nested element instead. That nested element has no width declaration, and can display the required padding, borders, and margins without encroaching on the parent element.

Now that you have a clear understanding of the CSS box model, you should also make yourself familiar with what’s commonly called the Internet Explorer 5 box model.

分享到:
评论

相关推荐

    完整css网站布局案例

    7. **Box Model**:理解CSS Box Model至关重要,它定义了元素占用的空间,包括内容、内边距、边框和外边距。正确地理解和应用Box Model可以帮助开发者精确控制元素的尺寸和间距。 8. **浏览器兼容性**:CSS3引入了...

    详解CSS中的Box Model盒属性的使用

    Box Model是CSS布局的核心概念,它定义了网页元素在页面上的占用空间,包括内容区域(content)、内边距(padding)、边框(border)和外边距(margin)四部分。理解Box Model对于精确控制元素的尺寸和布局至关重要。 正常...

    CSS高级教程

    6. **CSS盒模型 (CSS Box Model)**:盒模型是HTML元素占用空间的方式,包括内容(content)、内边距(padding)、边框(border)和外边距(margin)。理解盒模型是精确布局的基础,`box-sizing` 属性允许调整元素的盒模型...

    基于CSS Div的盒模型网页精确布局方法研究.pdf

    CSS Box Model. Retrieved from <https://www.w3.org/TR/CSS2/box.html> [2] Mozilla. (2020). Box model. Retrieved from <https://developer.mozilla.org/en-US/docs/Learn/CSS/Building_blocks/The_box_model> ...

    彻底弄懂CSS盒模型 Box Model

    【彻底弄懂CSS盒模型 Box Model】 在网页设计中,CSS盒模型是理解网页布局的基础。这个模型描述了网页元素如何占用空间并与其他元素交互。盒模型包括四个关键部分:内容(content)、内填充(padding)、边框...

    CSS 盒模型(Box Model)的学习和理解

    CSS盒模型(Box Model)的学习和理解一直是学习DivCSS网页布局的基础内容。但有很多CSS初学者依然不够熟悉,虽然我们提供了很多相关的教程。大家可以多学习与思考。今天发布一篇一位CSS初学者对CSS盒模型(Box Model...

    纯css3实现的滚筒洗衣机动画特效源码.zip

    2. 层叠上下文(CSS Box Model):理解元素如何在页面上布局和堆叠是非常重要的,CSS盒模型决定了元素的尺寸、位置以及与其他元素的关系。 3. CSS3转换(Transforms):通过transform属性,我们可以改变元素的位置...

    Learn CSS in One Day and Learn It Well (Volume 2)

    What is the CSS box model? How to position and float your CSS boxes How to hide HTML content How to change the background of CSS boxes How to use the CSS color property to change colors How to modify ...

    XHTMLCSS基础知识.pdf

    6. **CSS盒模型(CSS Box Model)** CSS盒模型包括内容(content)、内边距(padding)、边框(border)和外边距(margin)。理解盒模型对于精确控制元素尺寸和布局至关重要。 本教程旨在引导读者从表格布局过渡到基于Web...

    css-box-model:获取有关Element的准确且名称明确CSS Box模型信息:package:

    // profit安装 # # yarnyarn add css-box-model# npmnpm install css-box-model --save 箱型作品保证金箱边距+边框+填充+内容边框边框+填充+内容填充盒填充+内容内容盒内容这是我们返回的BoxModel : export ty

    CSS常见小问题解决

    #### 七、CSS Box Model 差异 **问题描述:** 在不同浏览器中,CSS盒模型的解析存在差异,尤其是在宽度计算上。 **解决方案:** 1. **IE与Firefox的差异:** - IE计算元素的实际宽度时会考虑内边距(`padding`)和...

    CSS3实现网页用户登陆界面带有动画背景特效源码.zip

    同时,理解CSS的层叠策略(CSS Box Model)对于正确应用样式至关重要。 2. **过渡(Transitions)**:CSS3的过渡效果用于平滑地改变元素从一种状态到另一种状态时的样式属性。例如,当鼠标悬停在按钮上时,可以使用...

    CSS盒模型的应用知识介绍,基础的CSS盒模型教学

    CSS盒模型(CSS Box Model)是一个核心的概念,它定义了元素如何在网页中呈现以及元素之间如何相互作用。简单来说,每个HTML元素都可以被视为一个矩形盒子,而这个盒子的大小、位置和样式都受到CSS盒模型的影响。 #...

    layerModel_seedz3k_box_model_

    Box model是CSS布局的核心,它决定了元素占用空间的计算方式。边距提供了元素周围的空白区域,边框则包围内容和内填充,内容区域则是元素实际显示文本或图像的地方。理解并熟练运用box model对于精确控制网页元素的...

    CSS3带有多级下拉菜单的弹性展开下拉动画效果源码.zip

    - 下拉菜单的实现基于层叠上下文(CSS Box Model),通过`position`属性(如`relative`, `absolute`, 或 `fixed`)来定位元素。 - 使用`z-index`控制元素的堆叠顺序,确保下拉菜单显示在正确的位置,不被其他元素...

    boxmodel:CSS盒模型编辑器界面构建器输入试用

    BoxModel-CSS盒子模型编辑器 BoxModel是一个jQuery插件,可帮助用户创建紧凑的表单输入,以编辑html表单中的box模型css。 它可以提交几个详细信息,例如单独的值以及可以在CSS块中使用的组合的优化单位。 它支持鼠标...

    情人节程序员用HTML网页表白【七夕烟花】 HTML5七夕情人节表白网页源码 HTML+CSS+JavaScript

    - **Box Model**:CSS盒模型定义了元素的布局方式,包括边距、边框、填充和内容区域。 - **示例**:`.content { padding: 80px 20px; }`。设置元素的内边距为上下80像素,左右20像素。 #### 2.2 Flexbox布局 - **...

    1+X认证Web前端开发初级模拟试题及答案6套.docx

    知识点:CSS Box Model, box-shadow 属性的使用。 13. 设置盒子圆角的属性是 `border-radius`。 知识点:CSS 盒子模型,border-radius 属性的使用。 14. 将 div 类名以 'c' 开头元素添加文字为红色,书写正确的...

    Web前端基础day03.zip

    2. **标准盒模型**(CSS Box Model):这是现代浏览器遵循的标准,宽度和高度只包含内容区域,不包括边框和内边距。默认情况下,大部分现代浏览器使用这种模型。如果需要将边框和内边距包含在内,可以使用`box-...

    15秋福师《网页设计技术》在线作业一[001].docx

    19. **CSS Box Model**:CSS的Box Model中,`Padding`属性的顺序是`top, right, bottom, left`,即上、右、下、左。 20. **JavaScript保留字**:`class`是JavaScript的保留字,不能用作变量或函数名,而`with`、`...

Global site tag (gtag.js) - Google Analytics