1. 基本概念:(content+padding+border+margin)
(包括标准模型和ie模型)2. 标准模型和ie模型的区别就是宽和高的计算方式不同
标准模型的宽指的是content的宽,ie模型的宽高是加上border和padding的长度的3. css是如何设置这种模型的
box-sizing: content-box(标准)--浏览器默认
box-sizing: border-box(ie)
4. js如何设置获取盒模型对应的宽和高
document.getElementsById(id)[0].style.width/height
// 局限性:只能取出内联样式的宽和高
document.getElementsById(id)[0].currentStyle.width/height
// 局限性:仅ie浏览器支持
window.getComputedStyle(dom).width/height
// 兼容性更好
document.getElementsById(id)[0].getBoundingClientRect().width/height;
// 也能拿到元素的宽和高,适用场景:计算元素的绝对位置
// 该方法返回元素的大小及其相对视口的位置
css属性的写法:
- 内联属性:直接往节点上内嵌
- 在页面中加入style节点
- 通过外联的css样式(link标签引入)
4.1 getBoundingClientRect();
let box = document.getElementsById(id)[0].getBoundingClientRect();
console.log('width',box.width) //容器的宽
console.log('height',box.height) //容器的高
console.log('top',box.top) // 容器相对于视口的高
console.log('right',box.right) // 容器最右边相对于视口的长度
console.log('bottom',box.bottom) // 容器最下边相对于视口的高
console.log('left',box.left) // 容器左边型对于视口的长度
console.log('x',box.x) // 容器左上角相对于视口的横坐标
console.log('y',box.y) // 容器左上角相对于视口的纵坐标
5. 根据盒模型解释边距重叠
BFC(是边距重叠解决方案)---(或者ifc)
-
基本概念: 块级格式化上下文
-
原理:bfc的渲染规则:
- 在bfc元素的垂直方向的边距会发生重叠
- bfc的区域不会与浮动元素的box重叠(用于清除浮动)
- bfc在页面上是一个独立的容器,外面的元素不会影响里面的元素,反过来,里面的元素也不会影响外面的元素
- 计算bfc高度的时候,浮动元素也会参与计算
-
如何创建bfc
- float为left或right
- position的值absolute或者fixed
- display的值是inline-block、inline-flex、inline-grid、flex、flow-root、grid、table-caption、table-cell;
- overflow:hidding/auto/overlay(不是visible)
-
bfc的使用场景: bfc子元素即使是float也会参与计算
例一:
<section class="father">
<article class="child">
</article>
</section>`
.father{
background-color: darkorange;
width: 200px;
/* overflow: hidden; */
/* 创建BFC */
}
.child{
height: 100px;
width: 200px;
margin-top: 10px;
background-color: darkolivegreen;
}
若不创建BFC
若创建BFC
例二: BFC垂直方向边距重叠
<section class="one">
<style>
.one{
background-color: pink;
overflow: hidden;
}
p{
margin: 5px auto 25px;
background-color: yellow;
}
</style>
<!-- 若没有设置bfc,则边距重叠,他们之间的边距取两个边距之间的最大值取最大值(25) -->
<!-- 取消边距重叠的办法:给子元素创建一个父元素
父元素创建一个bfc -->
<p>1</p>
<div style="overflow: hidden;">
<p>2</p>
</div>
<p>3</p>
</section>
例三
两个元素左边固定宽,有边自适应
<section class="layout">
<style>
.left{
float: left;
width: 100px;
height: 200px;
background-color: rosybrown;
}
.right{
height: 220px;
background-color: khaki;
<!--overflow: hidden;-->
<!--若不增加BFC,则右边元素溢出来向左浮动-->
}
</style>
<div class="left"></div>
<div class="right"></div>
</section>
例四: 清除浮动(BFC即使子元素是float也会参与高度计算)
<section class="clear">
<style>
.clear{
/* overflow: auto; */
/* 没有创建BFC,子元素是浮动元素的时候,高度不会计算进来
当把父级元素设置为BFC的时候,级元素的浮动元素的高度也会计算进来 */
background-color: red;
}
.float{
float: left;
font-size: 20px;
}
</style>
<div class="float">我是浮动元素</div>
</section>