【问题标题】:HTML Sibling Margins Affected受影响的 HTML 同级页边距
【发布时间】:2014-09-29 20:57:57
【问题描述】:

我正在尝试为容器 div 内的多个 div 元素设置边距。这是 HTML:

<div id="container">
    <div id="square"></div>
    <div id="square1"></div>
    <div id="square2"></div>
</div>

这里是 CSS:

#container {
    background: #ccc;
    width: 200px;
    height: 500px;
    position: absolute;
    overflow: initial;
}

#square {
    margin-top: 10px;
    height: 50px;
    background: green;
}

#square2 {
    margin-top: 275px;
    height: 55px;
    background: black;
}

现在,假设我要编辑正方形 1 的边距。这是更新后的 CSS:

#container {
    background: #ccc;
    width: 200px;
    height: 500px;
    position: absolute;
    overflow: initial;
}

#square {
    margin-top: 10px;
    height: 50px;
    background: green;
}

#square2 {
    margin-top: 275px;
    height: 55px;
    background: black;
}

#square1 {
    margin-top: 55px;
    height: 50px;
    background: red;
}

方块1的边距是正确的。但是,它弄乱了 square2 的边距,因为现在顶部边距是从 square1 而不是容器 div 测量的。如何将所有兄弟 div 的边距设置为从容器测量它们的位置,而不管其他兄弟 div 添加/删除了什么?任何帮助将不胜感激。

【问题讨论】:

  • 类 square 是否打算在这里的某个地方使用?
  • 不,我会删除它。
  • 我猜你可以使用position:absolutetop 属性将div 定位到容器中。

标签: css html margin margins


【解决方案1】:

你需要给position absolutewidth 100%;你可以检查js小提琴

Js fiddle

每个方格都这样

 #square {
    margin-top: 10px;
    height: 50px;
    background: green;
    position:absolute;
    width:100%;
 }

【讨论】:

    【解决方案2】:

    最好将这些方形 div 转储到相对 div 中,并为每个方形 div 设置一个绝对位置。你有点幸运,因为你知道每个方形 div 的高度。

    因此您的 HTML 保持不变。将绝对值放在相对值中的原因是,绝对值会出现在 #container 字段中,而不是正文中。

    但是您的 CSS 会发生变化:

    #container {
        background: #eee;
        width: 200px;
        height: 500px;
        position: relative;
        border: 10px solid green;
    }
    
    #square {
        margin-top: 10px;
        position: absolute;
        height: 50px;
        left: 0;
        right: 0;
        background: green;
    }
    
    #square2 {
        margin-top: 275px;
        height: 55px;
        position: absolute;
        background: black;
        left: 0;
        right: 0;
    }
    
    #square1 {
        margin-top: 55px;
        position: absolute;
        left: 0;
        right: 0;
        height: 50px;
        background: red;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      • 2014-01-08
      • 2019-05-18
      • 1970-01-01
      • 2013-03-30
      • 2014-05-23
      • 1970-01-01
      相关资源
      最近更新 更多