跳到主要内容

排除外部浮动

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

排除外部浮动是基于正常文档流中建立的 BFC 不得与元素本身所在的块格式化上下文中的任何浮动的外边距重叠。所以可以解决因为脱离文档流而导致的元素重叠问题。

一、形成


实时编辑器
function Test(props) {
  
  const container = {
    backgroundColor: "red"
  }
  const left = {
    width: "100px",
    height: "100px",
    float: "left",
    backgroundColor: "yellow"
  }
  const right = {
    width: "100px",
    height: "100px",
    backgroundColor: "blue"
  }

  return (
     <div style={ container }>
       <div style={ left }></div>
       <div style={ right }></div>
     </div>
  );
}
结果
Loading...

由上述背景可知: 有两个兄弟元素, 如果给第一个元素设置 float:left 浮动, 那么第一个元素会脱离文档流,浮动元素会与正常元素发生重叠

二、解决


2.1 正常元素添加overflow: auto

解决思路: 正常元素添加overflow:auto, 建立新的BFC。正常文档流中建立的 BFC 不得与元素本身所在的块格式化上下文中的任何浮动的外边距重叠

实时编辑器
function Test(props) {
  
  const container = {
    backgroundColor: "red",
    overflow: "auto"
  }
  const left = {
    width: "100px",
    height: "100px",
    float: "left",
    backgroundColor: "yellow"
  }
  const right = {
    width: "100px",
    height: "100px",
    overflow: "auto",
    backgroundColor: "blue"
  }

  return (
     <div style={ container }>
       <div style={ left }></div>
       <div style={ right }></div>
     </div>
  );
}
结果
Loading...

由上述解决可知: 通过设置overflow属性为正常元素创建了新的块级格式化上下文,所以这个新的块级上下文不会与任何浮动元素发生重叠。

2.2 正常元素添加display: flow-root

解决思路: 为正常元素设置display: flow-root, 建立新的BFC。正常文档流中建立的 BFC 不得与元素本身所在的块格式化上下文中的任何浮动的外边距重叠。注意: display: flow-root 不需要设置 width: <percentage>

实时编辑器
function Test(props) {
  
  const container = {
    backgroundColor: "red",
    display: "flow-root"
  }
  const left = {
    width: "100px",
    height: "100px",
    float: "left",
    backgroundColor: "yellow"
  }
  const right = {
    width: "100px",
    height: "100px",
    display: "flow-root",
    backgroundColor: "blue"
  }

  return (
     <div style={ container }>
       <div style={ left }></div>
       <div style={ right }></div>
     </div>
  );
}
结果
Loading...

2.2 正常元素添加display: inline-block

解决思路: 正常元素添加display: inline-block, 建立新的BFC。正常文档流中建立的 BFC 不得与元素本身所在的块格式化上下文中的任何浮动的外边距重叠。注意: display: inline-block 需要设置 width: <percentage>

实时编辑器
function Test(props) {
  
  const container = {
    backgroundColor: "red",
    display: "flow-root",
    fontSize: 0,
  }
  const left = {
    width: "100px",
    height: "100px",
    float: "left",
    backgroundColor: "yellow"
  }
  const right = {
    width: "100px",
    height: "100px",
    display: "inline-block",
    backgroundColor: "blue"
  }

  return (
     <div style={ container }>
       <div style={ left }></div>
       <div style={ right }></div>
     </div>
  );
}
结果
Loading...