跳到主要内容

阻止外边距重叠

2023年02月28日
柏拉文
越努力,越幸运

阻止外边距重叠 可以通过创建新的 BFC 避免两个相邻元素之间的外边距重叠。

一、形成


1.1 兄弟元素之间

同一层相邻元素之间: 相邻的两个元素之间的外边距重叠

实时编辑器
function Test(props) {
 const divStyle1 = {
    width: "200px",
    height: "200px",
    marginBottom: "30px",
    backgroundColor: "red",
 }
 const divStyle2 = {
    width: "200px",
    height: "200px",
    marginTop: "40px",
    backgroundColor: "blue",
 }
 

  return (
     <div>
       <div style={ divStyle1 }></div>
       <div style={ divStyle2 }></div>
     </div>
  );
}
结果
Loading...

现象: 两个兄弟元素发生折叠,折叠后的边距为40px

1.2 父子元素之间

没有内容将父元素和后代元素分开: 如果没有边框border,内边距padding,行内内容,也没有创建块级格式上下文或清除浮动来分开一个块级元素的上边界margin-top 与其内一个或多个后代块级元素的上边界margin-top;或没有边框,内边距,行内内容,高度height,最小高度min-height或 最大高度max-height 来分开一个块级元素的下边界margin-bottom与其内的一个或多个后代后代块元素的下边界margin-bottom,则就会出现父块元素和其内后代块元素外边界重叠,重叠部分最终会溢出到父级块元素外面。

实时编辑器
function Test(props) {
 const fatherSibling = {
    width: "200px",
    height: "200px",
    marginBottom: "40px",
    backgroundColor: "red",
 }
 const father = {
   width: "200px",
   height: "200px",
   backgroundColor: "black",
 }
 const son = {
    width: "100px",
    height: "100px",
    marginTop: "60px",
    backgroundColor: "blue",
 }
 

  return (
     <div>
         <div style={ fatherSibling }></div>
         <div style={ father }>
               <div style={ son }></div>
         </div>
     </div>
  );
}
结果
Loading...

如上所示: 给子元素son设置 margin-top,那么这个属性反而对父元素产生了同样的效果。

1.3 空块元素之间

空的块级元素: 当一个块元素上边界margin-top 直接贴到元素下边界margin-bottom时也会发生边界折叠。这种情况会发生在一个块元素完全没有设定边框border、内边距padding、高度height、最小高度min-height 、最大高度max-height 、内容设定为 inline 或是加上clear-fix的时候。

实时编辑器
function Test(props) {
 const sibling1 = {
    width: "200px",
    height: "200px",
    marginBottom: "60px",
    backgroundColor: "red",
 }
 const sibling2 = {
   marginTop: "20px",
   marginBottom: "20px"
 }
 const sibling3 = {
    width: "200px",
    height: "200px",
    marginTop: "60px",
    backgroundColor: "blue",
 }
 

  return (
     <div>
         <div style={ sibling1 }></div>
         <div style={ sibling2 }></div>
         <div style={ sibling3 }></div>
     </div>
  );
}
结果
Loading...

如上所示: sibling2 为空元素, 那么导致sibling1sibling3发生了边距重叠

二、解决


2.1 兄弟元素之间

查看

2.2 父子元素之间

查看

2.3 空块元素之间

查看