DIV,身高和浮动

时间:2013-04-23 19:57:19

标签: html css html5

我在蓝色div上有浮动红色div,如图片所示 enter image description here

<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>

我想这样做,所以蓝色div在红色DIV上有高度。当我删除浮动时,没关系。

5 个答案:

答案 0 :(得分:3)

你需要添加display:table-cell;或溢出:隐藏;你的蓝色div。这将为父母提供其子女的身高。

Demo

像这样:

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

旁注 - 你的div在浮动时需要宽度。

您还可以选择使用类蓝色浮点数创建div。但这可能会导致文档中出现一些不需要的行为(如果div不应该浮动)。

答案 1 :(得分:0)

只需浮动蓝色div:

.blue{
   float: left;
}

然后它将扩展以接受其子女的身高。

如果浮动不是一个选项,我会将display设置为inline-block,使其行为与浮动元素的行为相同。

.blue{
   display: inline-block;
}

参考:https://developer.mozilla.org/en-US/docs/CSS/display

答案 2 :(得分:0)

这是一个非常常见的问题,称为'clearfix'问题。可在此处找到更多信息(例如):Div rendering incorrectly in Firefox

简而言之,您应该向您的父(蓝色)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。虽然它们可能在某些情况下起作用,但它们几乎都有其他副作用,或者没有完全跨浏览器,因此应谨慎使用它们。

答案 3 :(得分: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;}

Example on jsfiddle

答案 4 :(得分: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>

相关问题