首页 > 开发 > CSS > 正文

详解CSS外边距折叠引发的问题

2024-07-11 08:42:30
字体:
来源:转载
供稿:网友

第一种:两个块级元素的上下边距折叠

第二种:父元素和子元素(或者最后一个元素)的外边距

第三种:空的块级元素的上下外边距

折叠的根本原因:

margin之间直接接触,没有阻隔

折叠后外边距的计算:

1.如果两个外边距都是正值,折叠后的外边距取较大的一个
2.如果两个外边距一正一负,折叠后的边距为边距之和
3.如果两个外边距都为负数,折叠后边距为较小的边距

解决方案:解决方法实际上也就是阻止外边距直接接触

第一种、第三种:只有静态流的元素才会发生外边距合并故设置float position inline-block都可以

<style>.bother{            width: 50px;            height: 50px;            margin: 50px;            background-color: #44cc00;            /*1.float: left;*/            /*2.position: absolute;*/            <!--3.display: inline-block;-->        }        /*.father{*/            /*2.position: relative;*/            /*background:#cccdd1;*/        /*}*/        /*.bother1{*/            /*2.top:50px;*/        /*}*/        /*.bother2{*/            /*2.top:250px;*/        /*}*/</style><body><div class="father"><div class="bother1 bother"></div><div class="bother2 bother"></div></div></body>

第二种(嵌套的情况)只要border padding非0或者有inline元素隔开,比如在父元素里加一行文字也可以

<style>        .margin-box{            width: 50px;            height: 50px;            /*margin: 50px;设置了上下左右的外边距*/            margin: 50px;            /*margin-left: 50px;*/            /*margin-right: 50px;*/            /*div是块级元素,所以设置左右外边距也不会使父元素有左右外边距*/            background-color: #fae900;            /*5.2 display: inline-block;*/        }        .father{            <!--3.overflow: hidden;-->            background:#cccdd1;            /*1.border: 1px solid;*/            /*2.padding: 20px;*/            /*5.1 display: inline-block;*/        /*如果没有border和padding只有测试这个字,那么子元素的外边距不会在父元素里显示*/        /*而仅仅只有上外边距显示,下外边距不显示*/        /*而如果在子元素下面同样写一个测试,那么下外边距也会显示*/        }    </style></head><body><div class="father">    <!--4.<span>测试</span>-->    <div class="margin-box"></div>    <!--4.<span>测试</span>--></div></body>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表