如何解决CSS外边距塌陷的问题

html-css012

如何解决CSS外边距塌陷的问题,第1张

首先我们先看出现外边距塌陷的三种情况: 1.当上下相邻的两个块级元素相遇,上面的元素有下边距margin-bottom,下面的元素有上边距margin-top,则它们之间的垂直距离取两个值中的较大者。 这时候两个盒子之间的垂直距离不是30px,而是20px。 解决方法: 尽量只给一个盒子添加margin值 2.对于两个嵌套关系的块元素,如果父元素没有上内边距及边框,父元素的上外边距会与子元素的上外边距发生合并,合并后的外边距为两者中的较大者。 这时候两个盒子会发生合并,上外边距为20px。 解决办法: ①给父元素定义上边框 ②给父元素定义上内边距 ③给父元素添加 overflow:hidden;④添加浮动 ⑤添加绝对定位 3.如果存在一个空的块级元素, border、padding、inline content、height、min-height 都不存在,那么上下边距中间将没有任何阻隔,上下外边距将会合并。 可以理解成中间div宽度为0且上下边距融合,只取margin的最大值。

<div>

    <p>Test</p>

</div>

<style>

div {

    width: 200px

    height: 200px

    background: #272727

    border: 1px #272727 solid

}

p {

    width: 158px

    line-height: 158px

    color: #fff

    text-align: center

    margin: 20px auto

    border-radius: 4px

    box-shadow: inset 0px 2px 8px 2px #000000

    border: 1px #666 solid

    border-left: 1px #131313 solid

    border-top: 1px #131313 solid

}

</style>

当圆角过大时深色边和高光边交界处会露陷,要不露陷的话:

边框渐变,貌似支持的浏览器少

不用边框,用两个div嵌套,外面那个比里面那个大1px,然后外面那个用45度的斜方向背景渐变(支持的浏览器多),里面那个用背景色加内阴影。

具体看应用场景,应用对的地方没有缺点。你根本不是真正了解这东西,在网上找两句话就来问。

你是完全不懂啊,说的自我感觉头头是道,要不是我多年经验都不能理解你说的话,方法很多,给你举几个例子

方法1、clear: both清除

.banyinglong{border:red solid 1px}

.banyinglong li{float:leftbackground: #ddd}

.clear{clear:both}

<ul class="banyinglong">

<li>1</li>

<li>2</li>

<li>3</li>

<div class="clear"></div>

</ul>

方法2、:after清除,与上一个原理一样

.banyinglong{border:red solid 1px}

.banyinglong:after{content:''display: blockclear: bothwidth:100%height: 0}

.banyinglong li{float:leftbackground: #ddd}

<ul class="banyinglong">

<li>1</li>

<li>2</li>

<li>3</li>

</ul>

方法3、display:flow-root是稍微新点的方法,基本很少有人用

.banyinglong{border:red solid 1pxdisplay:flow-root}

.banyinglong li{float:leftbackground: #ddd}

<ul class="banyinglong">

<li>1</li>

<li>2</li>

<li>3</li>

</ul>