CSS盒模型

css和模型的基本概念:

  包括:外边距(marign)、边框(border)、内容(content) 、内边距(padding)。

  css盒模型还区分:标准盒模型 和 IE盒模型

标准盒模型和IE模型区别:

  IE盒模型和标准模型的区别是:宽高的计算方式不同

  IE盒模型中,宽度为 左右边框的宽度 + 左右内边距的宽度+content;高度为:上下边框高度 + 上下内边距高度 + content 。如下图:

  

  标准盒模中,宽度为content的宽度;高度为content的高度。 如下图:

css如何设置这两种模型

  标准模型设置:box-sizing:content-box  (浏览器默认设置的是标准盒模型)

   IE模型设置:box-sizing: border-box

js如何设置获取盒模型对应的宽高

  1.dom.style.width/height (只适用内联样式的宽高,如果元素没有设置内联宽高则取不到值)

  2.dom.currentStyle.width/height (获取渲染后的宽高,但只适用于ie浏览器)

  3.window.getcomputedCurrentStyle(dom).width/height (获取渲染后的宽高,兼容性比较好)

  4. dom.getBoundingClientRect().width/height (计算元素的绝对位置,相对于视窗的左上角,可以获取到 width height top left right bottom)

nargin 纵向重叠问题

  * 相邻元素的 margin-top 和 margin-bottom 会发生重叠

  eg: 如下代码 aa 和 bb 之间的距离是多少

<style>
    div{
        height: 20px;
        margin-top: 10px;
        margin-bottom: 15px;
    }
</style>
<div>aa</div>
<div>bb</div>

  答案是: 15px

BFC(块级格式化上下文  Block format context)

  BFC的基本概念:块级格式化上下文

  BFC的原理(或者说BFC的渲染规则):

    1. 在同一个BFC中,两个相邻的元素垂直方向的外边距会重叠

    2. BFC的区域不会与浮动元素重叠

    3.BFC是一个独立的容器,外面的元素不会影响子元素,反之BFC里面的子元素也不会影响外面的元素

    4. 计算BFC的高度时,浮动元素也参与计算

  如何创建BFC:

    1. float 值不为none

    2. position 的值为:absolute 后者 fixed

    3. distable 的值为: table 、table-cell 、table-caption 、flex 、inline-block

    4.块级元素设置overflow,并且值不为visible.

  BFC用途:

    1.清除浮动

      浮动元素的父级的高度不能被撑开,可以为父元素设置:overflow:hidden 。

    2.解决外边距重叠问题

      例子:

style>
   html,body{
       margin:0;
       height:100%;
   }
  div{
       100px;
      height: 100px;
      background:red;
  }
    .top{
        margin-bottom:100px;
    }
   .bottom{
       margin-top:50px;
   }
</style>
<div class="top">1</div>
<div class="bottom">2</div>

运行可以看到这两个div中间的距离是100px,而不是150px。这就是因为边距重叠了。

解决方案就是为其中一个元素外面加一层元素,并为这个元素设置:overflow:hidden 。使其形成BFC。BFC内部是一个独立的容器,不会与外部相互影响,可以防止margin重叠。

<style>
   html,body{
       margin:0;
       height:100%;
   }
   .top,.bottom{
       100px;
      height: 100px;
      background:red;
  }
   .top{
        margin-bottom:100px;
   }
   .bottom{
       margin-top:50px;
   }
</style>
<div style="overflow:hidden;">
    <div class="top">1</div>
</div>
<div class="bottom">2</div>

  

原文地址:https://www.cnblogs.com/yangkangkang/p/8665794.html