来自外部DIV的边距底部不起作用

时间:2017-12-05 10:04:58

标签: html css margin

我想创建一个外部DIV,它包含几个内部DIV。目前,这是完美的。 但是我对外部div的边缘有一些麻烦。如果外部DIV具有固定高度(f.ex.height:100px;),则底部将有一个边距。但是如果我将高度设置为auto(它应该只有所有内部DIV的高度),则margin-bottom会消失。

示例:

此处,保证金底部正常适用。外框的高度设置为固定高度: https://jsfiddle.net/v81mehc5/3/

但是将外部DIV的高度从固定高度(75px)更改为auto,40px的边距底部消失。 https://jsfiddle.net/v81mehc5/2/

第二种情况中缺少什么?什么是错误的?

HTML

text before

<div class="outer-box">
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
</div>

text after

CSS

.outer-box
{
  width: 200px;
  height: 75px; /*if height: auto > no margin-bottom will be applied*/
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}

非常感谢你的帮助。

2 个答案:

答案 0 :(得分:3)

没有什么遗漏,但你在外部div中使用浮动元素。所以height:auto在你的情况下意味着height:0,所以你只看到边距底部(你认为它是高度)。

enter image description here

要解决此问题,您需要将overflow:hidden添加到外部div。

&#13;
&#13;
.outer-box
{
  width: 200px;
  height: auto;
  overflow:auto;
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}
&#13;
text before

<div class="outer-box">
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
</div>

text after
&#13;
&#13;
&#13;

有关同一问题的更多问题以获取更多详细信息:

Why does overflow hidden stop floating elements escaping their container?

CSS overflow:hidden with floats

答案 1 :(得分:1)

浮动元素会折叠其容器。如果你对它应用边框,你会看到:

<div style="border: 1px solid #666; margin-bottom: 40px;">
<div style="float: left; height: 100px; border: 1px solid #999; width: 49%;"></div>
<div style="float: right; height: 100px; border: 1px solid #999; width: 49%;"></div>
</div>
Text

您可以使用清除技术来解决这个问题,作为可在IE8及更高版本中运行的解决方案:

.clearfix:after {
    content: "";
    display: table;
    clear: both;
}

  .clearfix:after {
      content: "";
      display: table;
      clear: both;
  }
<div style="border: 1px solid #666; margin-bottom: 40px;" class="clearfix">
<div style="float: left; height: 100px; border: 1px solid #999; width: 49%;"></div>
<div style="float: right; height: 100px; border: 1px solid #999; width: 49%;"></div>
</div>
Text

相关问题