跳到主要内容

盒模型 与 BFC

盒模型包含

  • content
  • padding
  • border
  • margin

IE模型

IE5.5以及更早的IE浏览器使用的盒模型

widthheight 包含了 contentpaddingborder

css设置: box-sizing: border-box;

标准模型

现代浏览器默认使用标准模型

widthheight 只包含content

css设置: box-sizing: conent-box;

JS如何设置获取盒子模型对应的宽和高

dom.style.width = '888px';  // 设置
window.getComputedStyle(dom).width; // 获取 标准模型下的宽度,不包含 padding和border
dom.getBoundingClientRect().width; // 受 box-sizing 设置影响,box-sizing: border-box时,包含 padding和border

BFC(块级格式化上下文)

  • Block Formatting Contexts

  • 一个隔离了外界的独立容器,容器里面的元素不会在布局上影响到外面的元素

  • BFC 具有普通容器所没有的一些特性:

    • 同一个 BFC 下外边距会发生折叠 => 不同BFC可以避免外边距折叠margin-collapse
    • BFC 可以包含浮动的元素
    • BFC 可以阻止元素被浮动元素覆盖
  • 触发BFC的条件:

    • html 根元素
    • 浮动元素: floatnone 以外的值
    • 绝对定位元素: position (absolutefixed)
    • displayinline-blocktable-cellsflex...
    • overflow 除了 visible 以外的值 (hiddenautoscroll)

应用: 清除浮动

1. 清除浮动的办法

  • 浮动元素的兄弟节点,添加clear:both
  • 父元素的:after伪类,添加clear:bothzoom: 1(IE转有属性)可解决ie6,ie7浮动问题
  • 父元素添加overflow: hidden
  • 父元素添加display: table
  • ...

2.手写 clearfix

.clearfix:after {
content: '';
display: block;
clear: both;
}