CSS盒模型

什么是盒模型?

在HTML页面中,每一个元素都可以看做事一个盒子;而这个盒模型由:内容区(content)、填充区(padding)、边框区(border)、外边界区(margin)四部分组成。
在这里插入图片描述

盒模型有哪两种?

标准模式下:一个块的总宽度(页面中占的宽度)=width+margin(左右)+padding(左右)+border(左右)
怪异模式下:一个块的总宽度=width+margin(左右)(width已经包含了padding和padding值)

标准和怪异模型的转换

box-sizing:content-box;将采用标准模式下的盒子模型;
box-sizing:border-box;将采用怪异模式下的盒子模型;
box-sizing:inherit;规定应从父元素继承 box-sizing 属性的值。

JS盒模型

在这里插入图片描述
JS中怎么获取和设置box的内容宽高:
在IE中:dom.currentStyle.width/height;
在非IE中:window.getComputedStyle(dom).width/height


var obj = document.getElementById("box");

var style = null;
if (window.getComputedStyle) {
    style = window.getComputedStyle(obj, null);    // 非IE
} else { 
    style = obj.currentStyle;  // IE
}
alert("width=" + style.width + "\nheight=" + style.height);

盒模型产生的双边距重叠问题解决

可以使用BFC(块级格式化上下文)解决

有两种双边距重叠的情况

父子关系的边距重叠:

父子关系,如果子元素设置了外边距,在没有把父元素变成BFC的情况下,父元素也会产生外边距
给父元素添加overflow:hidden
这样父元素就会变为BFC,不会随子元素产生外边距

<style>
.out {
background-color: #f00;
width: 200px;
height: 200px;
}

.inner{
margin-top: 50px;
width: 100px;
height: 100px;
background-color: blue;
}   
</style>
<div class="out">
    <div class="inner"></article>
</div>


同级兄弟关系的重叠:

同级元素在垂直方向上外边距会出现重叠情况,最后外边距的大小取两者绝对值大的那个
可通过添加空元素或伪类元素,设置overflow:hidden;解决margin重叠问题

  <style type="text/css">
            .fat {
                background-color: #ccc;
            }
            .fat .child-one {
                width: 100px;
                height: 100px;
                margin-bottom: 50px;
                background-color: #f00;
            }

            .fat .child-two {
                width: 100px;
                height: 100px;
                margin-top: 20px;
                background-color: #345890;
            }
            .fat .child-content{
				overflow:hidden
			}
        </style>
   <section class="fat">
        <div class="child-top"></div>
        <div class="child-content"></div>
        <div class="child-bottom"></div>
    </section>

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值