DIV,高度和浮动

6
我在蓝色div上放置了浮动的红色div,就像图片上展示的那样。
<div class="blue">
  <div style="height: 40px; float: left"></div>
  <div style="height: 40px; float: left"></div>
  <div style="height: 40px; float: left"></div>

  <div style="height: 40px; float: left"></div>
  <div style="height: 40px; float: left"></div>
  <div style="height: 40px; float: left"></div>
</div>

我希望这个蓝色的区块可以覆盖在红色区块上方,当我去掉float属性时可以达成。

5个回答

3
你需要在蓝色div上添加display:table-cell;或overflow:hidden;。这将使父元素具有其子元素的高度。

Demo

像这样:
.blue{
   overflow:hidden;
   //or
   //display:table-cell;
}

一个侧注 - 当div浮动时,它们需要一个宽度。

您还可以选择使具有蓝色类的div浮动。但是这可能会导致文档中一些不必要的行为(如果该div不应该浮动)。


@PeterVR 但实际上没有内容可显示,这只是为了演示目的。 - RelevantUsername

0

只需将蓝色 div 浮动:

.blue{
   float: left;
}

然后它将扩展以适应其子元素的高度。

如果不能使用浮动,我会将display设置为inline-block,使其与浮动元素的行为相同。

.blue{
   display: inline-block;
}

参考资料:https://developer.mozilla.org/zh-CN/docs/Web/CSS/display


0

这是一个非常常见的问题,被称为“clearfix”问题。可以在此处找到更多信息(例如):Firefox中Div渲染不正确

简而言之,您应该向父级(蓝色)div添加一个类.clearfix,看起来像这样:

.clearfix {
  *zoom: 1;
}
.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
    line-height: 0;
  }
&:after {
    clear: both;
}

这个来自 Twitter Bootsrap,但有很多其他替代方案。关于为什么和如何工作,建议谷歌搜索“clearfix”。

请注意,还存在其他“解决方案”,例如使用inline blocks、添加overflow: hidden甚至显示为table-cell。虽然它们在某些情况下可能有效,但它们几乎都有其他副作用,或者不是完全跨浏览器的,因此应谨慎使用。


0

如果你需要更加简洁和动态的东西,请尝试这个:

<div class="blue">
<div>
    <div></div>
    <div></div>
    <div></div>
</div>
<div>
    <div></div>
    <div></div>
    <div></div>
</div>

还有这个:

.blue {background-color: blue;text-align: center;display: inline-block;padding: 5px;}
.blue > div > div {background-color: red; width:100px; height: 50px; margin: 10px;display: inline-block;}

在jsfiddle上的示例


0

另一种选项是在所有浏览器中不兼容的选项,但无需使用float:left。

.blue{
    background-color:blue;
    overflow:hidden;
    width: 140px;
    display: flex;
    justify-content: space-around;
    flex-wrap: wrap;
}

.blue div{
    background-color:red;
    margin: 2.5px 0 2.5px 0;
    width:40px;
}
<div class="blue">
  <div style="height: 40px;"></div>
  <div style="height: 40px;"></div>
  <div style="height: 40px;"></div>

  <div style="height: 40px;"></div>
  <div style="height: 40px;"></div>
  <div style="height: 40px;"></div>
</div>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接