css盒模型
- 基本概念: 标准盒子 + IE盒子模型
盒模型包含了元素的margin/border/padding/content(元素内容) - 标准模型与IE模型的区别
宽度/高度计算方式不同- 标准盒子模型 width = content的宽度
height = content的高度 - IE盒子模型 width = content的宽度 + padding + border
height = content的高度 + padding + border
- 标准盒子模型 width = content的宽度
- css如何设置这两种模型
- 标准盒模型
box-sizing: content-box;(默认) - IE盒模型
box-sizing: border-box;
- 标准盒模型
- js如何获取盒模型对应的宽和高
- dom.style.width/height (适用于内联样式的宽高)
- dom.currentStyle.width/height(只兼容IE浏览器)
- widows.getComputedStyle(dom).width/height(兼容IE8以上的浏览器/火狐浏览器以及谷歌浏览器)
- dom.getBoundingClientRect().width/height(兼容性最好)
- 实例题(根据盒模型解释边据重叠)
- BFC(边距重叠的解决方案)
-
BFC(块级格式化上下文)
-
BFC的原理
- 垂直方向发生重叠
- BFC区域不会与浮动元素的box发生重叠
- 它是一个独立的容器
- 计算BFC的高度时,浮动元素也参与计算
-
如何创建BFC
- overflow 不为 visible
- display 的值是inline-block、table-cell、flex、table-caption或者inline-flex
- float 不为 none
- position 不为 static/relative
-
BFC的使用场景
- 创建BFC避免margin重叠
- BFC元素不与float元素重叠(自适应两栏布局)
- 清除浮动
例子:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>盒模型</title> <style> * { padding: 0; margin: 0; } p { background: red; height: 200px; line-height: 200px; text-align: center; color: white; margin: 30px; } </style> </head> <body> <!-- margin合并 --> <p>1</p> <p>2</p> <p>3</p> <!-- 场景1 --> <!-- 创建BFC避免margin重叠 --> <p>1</p> <div style="overflow: hidden;"> <p>2</p> </div> <p>3</p> <!-- 场景2 --> <!-- 自适应两栏布局 --> <!-- 不创建BFC,高度大于左栏元素,内容100%显示 --> <!-- BFC元素不与float元素重叠 --> <div class="container"> <style> .left { float: left; width: 20%; height: 200px; background: pink; } .right { height: 300px; background: orange; /* BFC元素不与float元素重叠 */ overflow: auto; } </style> <div class="left">left</div> <div class="right">right</div> </div> <!-- 场景3 --> <!-- 子元素浮动,父元素不设置样式的情况下,父元素的高度为0 --> <!-- 清除浮动 --> <!-- 方法:父元素创建BFC --> <div class="float"> <style> .float { /* 父元素创建BFC */ overflow: auto; } .children { float: left; background: orangered; } </style> <div class="children">children</div> </div> </body> </html>
-