跳到主要内容

兄弟元素

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

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

一、形成


实时编辑器
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

二、解决


2.1 后面元素添加float: left

实时编辑器
function Test(props) {
    const container = {
        height: "500px"
    }
    const divStyle1 = {
        width: "200px",
        height: "200px",
        marginBottom: "30px",
        backgroundColor: "red",
    }
    const divStyle2 = {
        float: "left",
        width: "200px",
        height: "200px",
        marginTop: "40px",
        backgroundColor: "blue",
    }
    
    return (
        <div style={ container }>
            <div style={ divStyle1 }></div>
            <div style={ divStyle2 }></div>
        </div>
    );
}
结果
Loading...

2.2 后面元素添加position: absolute

实时编辑器
function Test(props) {
    const container = {
        height: "500px"
    }
    const divStyle1 = {
        width: "200px",
        height: "200px",
        marginBottom: "30px",
        backgroundColor: "red",
    }
    const divStyle2 = {
        position: "absolute",
        width: "200px",
        height: "200px",
        marginTop: "40px",
        backgroundColor: "blue",
    }
    
    return (
        <div style={ container }>
            <div style={ divStyle1 }></div>
            <div style={ divStyle2 }></div>
        </div>
    );
}
结果
Loading...

2.3 后面元素添加display: inline-block

实时编辑器
function Test(props) {
    const divStyle1 = {
        width: "200px",
        height: "200px",
        marginBottom: "30px",
        backgroundColor: "red",
    }
    const divStyle2 = {
        display: "inline-block",
        width: "200px",
        height: "200px",
        marginTop: "40px",
        backgroundColor: "blue",
    }
    
    return (
        <div>
            <div style={ divStyle1 }></div>
            <div style={ divStyle2 }></div>
        </div>
    );
}
结果
Loading...

注意: IE6IE7下不完全支持display:inline-block, 所以要加上display:inline;zoom:1即可解决IE67的``bug;