首页 > 解决方案 > 边距底部不适用于包含三个浮动 div 的 div

问题描述

* {
  box-sizing: border-box;
}

.box {
  float: left;
  width: 33.33%;
  padding: 50px;
}
<h2>Grid of Boxes</h2>
<p>Float boxes side by side:</p>

<div class="big-box" style="margin-bottom:30px;">
  <div class="box" style="background-color:#bbb">
  <p>Some text inside the box.</p>
  </div>
  <div class="box" style="background-color:#ccc">
  <p>Some text inside the box.</p>
  </div>
  <div class="box" style="background-color:#ddd">
  <p>Some text inside the box.</p>
  </div>
</div>

<p style="clear:both;">Note that we also use the clearfix hack to take care of the layout flow, and that add the box-sizing property to make sure that the box doesn't break due to extra padding. Try to remove this code to see the effect.</p>

在上面的代码中margin-bottom:30px不起作用。为什么???我还需要建议如何在这种场景中应用边距底部。我对 CSS 很陌生,这可能是一个非常愚蠢的问题,或者代码可能包含一些愚蠢的错误。divclass = big-box

标签: javascripthtmlcss

解决方案


要回答您的问题:

  1. 您的大框的边距底部正在工作,但与 3 个浮动框相比,30px 仍然很小。所以当你看它时,它看起来不像是大盒子包裹着 3 个盒子。

有2个解决方案:

  1. 指定一个大于或至少等于 3 个浮动框的高度。
  2. 从你的盒子类中删除 float:left 并给出大盒子 display:flex 和 100% 宽度

下面的示例是第二种解决方案。

      * {
        box-sizing: border-box;
      }
      .box{
        width:33.33%;
        padding:50px;
      }
      .big-box{
        display:flex;
        margin-bottom:30px;
        width:100%;
      }
<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <h2>Grid of Boxes</h2>
    <p>Float boxes side by side:</p>

    <div class="big-box" >
      <div class="box" style="background-color:#bbb">
        <p>Some text inside the box.</p>
      </div>
      <div class="box" style="background-color:#ccc">
        <p>Some text inside the box.</p>
      </div>
      <div class="box" style="background-color:#ddd">
        <p>Some text inside the box.</p>
      </div>
    </div>

    <p style="clear:both;">
      Note that we also use the clearfix hack to take care of the layout flow,
      and that add the box-sizing property to make sure that the box doesn't
      break due to extra padding. Try to remove this code to see the effect.
    </p>
  </body>
</html>

希望这是您正在寻找的答案。


推荐阅读