CSS盒模型的概念与分类
CSS盒模型就是一个盒子,封装周围的HTML元素,它包括内容content、边框border、内边距padding、外边距margin。
CSS盒模型分为标准模型和IE模型;
标准模型和IE模型的区别
标准模型的width是内容content 的宽度; 设置方式: box-sizing:content-box;
IE模型的width是内容content + 边框border + 内边距paddig 的宽度; 设置方式: box-sizing:border-box;
通过js如何获取盒模型的宽高
1.dom.style.width/height 只能获取到dom的内联样式
2.dom.currentStyle.width/height 获取到的是dom的实际宽高,但这种方式只在IE中可以使用
3.window.getComputedStyle(dom,null).width/height 获取到的是dom的实际宽高,但是不支持IE
4.dom.offsetWidth/offerHeight 最常用的,兼容性最好的
第2,3个组合下就可以兼容ie与其他浏览器了
window.getComputedStyle ? window.getComputedStyle(obj,null).width : obj.currentStyle.width;
边距重叠
边距重叠就是相邻元素的边距重叠在一起,出现了预期外的布局。比如子元素设置了margin-top,父元素没有设置,但是父元素也有了上边距。
<!DOCTYPE html><html><head> ???<title>边距重叠</title> ???<meta charset="utf-8"> ???<style type="text/css"> ???????html *{ ???????????margin: 0; ???????????padding: 0; ???????} ???????.content{ ???????????width: 500px; ???????????height:100px; ???????????background: green; ???????} ???????.parent{ ???????????width: 300px; ???????????height: 300px; ???????????background: pink; ???????} ???????.child{ ???????????width: 150px; ???????????height: 150px; ???????????background: yellow; ???????????margin-top: 50px; ???????} ???</style></head><body> ???<div class="content"> ???????占位内容区域 ???</div> ???<div class="parent"> ???????<div class="child"> ???????????????????</div> ???</div></body></html>
下图就是代码运行结果:
解决边距重叠-BFC
1、BFC概念:块级格式化上下文
2、BFC的原理:
BFC的区域不会与浮动区域重叠
计算BFC区域高度时,浮动区域也参与计算
BFC区域是独立的一个区域,不与其他区域相互影响
3、如何创建BFC
脱离文档流:float不为none;position为absolutely或fixed
overflow不为visible(如overflow:hidden)
display为“table-cell”, “table-caption”, “inline-block”中的任何一个
4、BFC应用场景
自适应两栏布局
清除浮动
防止垂直margin重叠
CSS盒模型的介绍
原文地址:https://www.cnblogs.com/menggirl23/p/10068259.html