【问题标题】:Keeping the distance between 2 divs constant保持2个div之间的距离不变
【发布时间】:2015-06-03 02:46:17
【问题描述】:

我有以下 HTML 标记 -

<div class="bar">
<p> Example Text </p>
</div>

<div class="dynamic-height">
 <div class="box">
  <p> Example Text 1</p>
 </div>
</div>

<div class="footer">
This is footer
</div>

和下面的 CSS -

.bar{
     height:20px;
     width:100%;
    }
 .box
    {
      float:left;
      width:50px
      height:50px;
      border:1px solid black;
    }
.dynamic-height
    {
     min-height:50px;
     width:100%;
    }
. body
    {
       height:200px;
    }
.footer
    {
    height:20px;
    position:relative;
    bottom:0;
    }

以下是这些 div 的预期规则 -

  1. “动态高度”类的 div 会有更多

    元素 使用javascript动态添加到它。所以它的高度是 动态

  2. 具有“footer”类的 div 必须始终位于底部,并且动态高度和 footer div 之间的距离应始终为 10px; (边距:10px)

解决问题 -

当我使用javascript添加一个动态“p”元素到具有类“dynamic-height”的div时,这个div的高度会增加,如果我继续添加“p”元素,高度会增加,然后它与页脚 div 重叠。

我只想在页脚 div 和动态高度 div 之间始终保持 10 像素的距离

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    只需将 margin-top 添加到页脚以始终拥有 10 像素的空间

    .footer
    {
        margin-top: 10px;
        height:20px;
        position:relative;
        bottom:0;
    }
    

    【讨论】:

    • 这似乎不起作用。我想我无法在这里解释我的担忧。
    • 我做了一个jsfiddle 并且能够找出路
    【解决方案2】:

    清除.box div 上的.footer div 中的左浮动:

    .footer{
        height:20px;
        position:relative;
        bottom:0;
        clear:left;
        margin-top:10px;
    }
    

    应该这样做。 .footer div 挂在重新定位的.box div 上。

    【讨论】:

    • 您的 clear:left 为我指明了我正在寻找的解决方案。由于动态高度 div 的高度是动态的,添加 overflow:scrollheight 将高度固定为它可以扩展的最大值。
    【解决方案3】:

    在您的 .dynamic-height 类中添加 margin-bottom 如下margin-bottom :10px;

    【讨论】:

    • 感谢您的建议,但它似乎没有用。反正已经更新了答案。
    【解决方案4】:

    这是JSFiddle,就我的问题而言,这将使我的情况变得清晰。

    <div class="bar">
    <p> Example Text </p>
        <input type="button" onclick="add();" value="Add box"/>
    </div>
    
    <div class="dynamic-height" id="dyn">
         <div class="box">
          <p> Example Text 1</p>
         </div>        
    </div>
    <div class="footer">
    This is footer
    </div>
    

    我能够从 tahdhaze09 获得提示,并将其与将溢出属性设置为 auto 结合使用,用于动态高度 div。

    作为我最初的问题,也许不够清楚,是使两个 div 之间的距离保持不变,其中一个是动态高度。所以对于这个 div,overflow 属性起到了神奇的作用

    【讨论】: