好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

首先我们先看出现 外边距 塌陷的三种情况:

1.当上下相邻的两个块级元素相遇,上面的元素有下 边距 m arg in-bottom,下面的元素有上边距mar gin -t op,则它们之间的垂直 距离 取两个值中的 较大 者。

<style>
  .box1 {
     width: 150px;
     h ei ght: 100px;
     margin-bottom: 20px;
     background-color: rgb(201, 239, 98);
  }
  .box2 {
     width: 100px;
     height: 100px;
     background-color: rebeccapurple;
     margin-top: 10px;
  }
</style>
   <div class="box1"></div>
   <div class="box2"></div>

这时候两个 盒子 之间的垂直距离不是30px,而是20px。

解决方法:

尽量只给一个盒子添加margin值

2.对于两个嵌套关系的块元素,如果父元素没有上 内边距 及边框,父元素的上外边距会与子元素的上外边距发生合并,合并后的外边距为两者中的较大者。

<style>
        .box1 {
            width: 150px;
            height: 100px;
            margin-top: 20px; 
            /* border: 1px solid  # 000000; */
            background-color:  red ;
        }

        .box2 {
            width: 100px;
            height: 100px;
            /* border: 1px solid #000000; */
            background-color: rebeccapurple;
            margin-top: 10px;
        }
    </style>
</head>

<body>
    <div class="box1">
        <div class="box2"></div>
    </div>
</body>

这时候两个盒子会发生合并,上外边距为20px。

解决办法:

①给父元素定义上边框

②给父元素定义上内边距

③给父元素添加 overflow:hidden;

④添加浮动

⑤添加绝对定位

3.如果存在一个空的块级元素,border、padding、inline content、height、min-height都不存在,那么上下边距中间将没有任何阻隔,上下外边距将会合并。

<p style=" ;m argin-bottom: 0px;">这个段落的和下面段落的距离将为20px</p>

<div style="margin-top: 20px; margin-bottom: 20px;"></div>

<p style="margin-top: 0px;">这个段落的和上面段落的距离将为20px</p>

可以理解成中间div 宽 度为0且上下边距融合,只取margin的最大值。

到此这篇关于CSS中如何解决外边距塌陷问题的 文章 就介绍到这了,更多相关CSS外边距塌陷内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!

总结

以上是 为你收集整理的 CSS中如何解决外边距塌陷问题 全部内容,希望文章能够帮你解决 CSS中如何解决外边距塌陷问题 所遇到的问题。

如果觉得 网站内容还不错, 推荐好友。

查看更多关于CSS中如何解决外边距塌陷问题的详细内容...

  阅读:25次