【问题标题】:giving child div a margin relative to the parent div [duplicate]给子div相对于父div的边距[重复]
【发布时间】:2014-11-15 19:47:44
【问题描述】:

这是我的html:

<div class='parentDiv'>
    <div class='childDiv'></div>
</div>

这是我的 CSS:

.parentDiv {
    margin-top: 200px;
    width: 700px;
    height: 800px;
    background-color: red;
}

.childDiv {
    background-color: green;
    width: 50px;
    height: 50px;
    margin-top: 22px;
}

小提琴:http://jsfiddle.net/1whywvpa/

为什么 childDiv 没有得到 22px 的 margin-top?如果像素大于已提供给 parentDiv 的 200px,它只会获得一个边距顶部。有什么方法可以让 childDiv 获得相对于 parentDiv 22px 的父 div 而无需执行某种类型的“给父 div 1px 填充”hack?

【问题讨论】:

  • position: absolute;.childDiv 会起作用,但我不确定你会使用它。
  • @MaryMelody 是的,我不想使用 position:absolute;
  • display: inline-block; 设置为.childDiv.parentDiv - jsfiddle.net/1whywvpa/2
  • @MaryMelody 谢谢,我想我最喜欢你的解决方案,因为我不想绝对定位 div,也不想让 childDiv 向左浮动。把它记下来作为答案,我会标记它。

标签: html css margin


【解决方案1】:

也许这会有所帮助:CSS Margins Overlap Problem

为两个元素添加位置属性。父母是relative,孩子是absolute...

.parentDiv {
    position: relative;
    margin-top: 200px;
    width: 700px;
    height: 800px;
    background-color: red;
}

.childDiv {
    position: absolute;
    background-color: green;
    width: 50px;
    height: 50px;
    margin-top: 22px;
}

这是你的小提琴:http://jsfiddle.net/algorhythm/1whywvpa/5/

【讨论】:

  • 我想这样做而不将 childDiv 设置为 position: absolute 或使其浮动。我发现 'display: inline-block' 是我的最佳解决方案。
【解决方案2】:

在这种情况下,您不想使用边距。您应该向父 div 添加填充。您还需要关闭您的父 div。所以删除子div上的margin-top:22px。在父 div 上添加padding-top:22px;

【讨论】:

    【解决方案3】:

    使子 div 占包含父 div 的百分比:

    .parentDiv {
        position: relative;
        margin-top: 200px;
        width: 700px;
        height: 800px;
        background-color: red;
        }
    
    .childDiv {
        position: absolute;
        background-color: green;
        width: 7%;
        height: 6%;
        margin-top: 1%;
        }
    

    【讨论】:

      【解决方案4】:

      看起来.childDiv 没有向左浮动。

      如果你 float: left;.childDiv,就像我在 JS Fiddle 中所做的那样,它将根据需要应用边距。

      【讨论】:

      • 如果我不希望 childDiv 向左浮动,有什么办法吗?
      • display: inline-block; 设置为.childDiv.parentDiv - jsfiddle.net/1whywvpa/2jsfiddle.net/1whywvpa/6
      • @MaryMelody 或给父母一个overflow: hiddenpadding-top: 1px;border-top: 1px solid transparent;。这是由Collapsing margins 引起的。
      • @HashemQolami 是的!谢谢! 我记得你之前告诉过我关于折叠边距的事。 :)
      猜你喜欢
      • 2013-06-12
      • 1970-01-01
      • 2015-03-25
      • 1970-01-01
      • 2018-07-27
      • 2023-04-01
      • 2023-04-07
      • 1970-01-01
      • 2020-02-13
      相关资源
      最近更新 更多