首页 > 解决方案 > 在新行上浮动 div 不获取整个空间

问题描述

我有这个例子,我希望最后一个 div 向上移动以填充其上方的空间:

*{
  box-sizing: border-box;
}
.container{ 
  width: 600px;
border: 2px solid red;
height: 100%;
 
}
.container::after{
  content: "";
    clear: both; 
  display: table;
}
.child{
  width: calc(50% - 4px);
  border: 2px solid black;
  float: left;
}
<div class="container">
  
<div class="child">
  Hello
  <br/>hello
  <br/>hello
  <br/>hello
  <br/>hello
</div>
<div class="child"> <br/>hello
  <br/>hello
  <br/>hello</div>
<div class="child"> <br/>hello
  <br/>hello
  <br/>hello</div>
<div class="child"> 
  <br/>How can I make this shift up in the white space that is available above?
  <br/>
  <br/>
  </div>
  
</div>

在左下角的 div 中,顶部有空白我想将 div 向上移动,我该怎么做?谢谢你。

标签: htmlcss

解决方案


在这种情况下,最后一个元素不会“弹出”来填充其上方的空白。

div为什么不使用 float ,为什么不使用 flexbox 呢?通过将.container显示设置为 usingflex并使其包裹弹性项目,它将自动填充所需的空间。

下面的片段说明了:

*{
  box-sizing: border-box;
}
.container{ 
  width: 600px;
  border: 2px solid red;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
}
.container::after{
  content: "";
  clear: both; 
  display: table;
}
.child{
  width: 50%;
  border: 2px solid black;
}
<div class="container">
  
<div class="child">
  Hello
  <br/>hello
  <br/>hello
  <br/>hello
  <br/>hello
</div>
<div class="child"> <br/>hello
  <br/>hello
  <br/>hello</div>
<div class="child"> <br/>hello
  <br/>hello
  <br/>hello</div>
<div class="child"> 
  <br/>How can I make this shift up in the white space that is available above?
  <br/>
  <br/>
  </div>
  
</div>


推荐阅读