浮动元素进入下一个框

Float element goes into the next box

当我将 float 添加到第一个元素时,它只是进入了第二个块。这是什么原因?

在此处检查 fiddle: https://jsfiddle.net/peterzhong/33m7k5gy/9/

.container {
  position:relative;
  width:10em;
  height:10em;
  background:#aaa;
  float:left;
}
.positioned {
  position:absolute;
  top:50%;
  left:50%;
  bottom:0;
  right:0;
  background:#FFA500; 
}
.container1 {
  position:relative;
  width:10em;
  height:10em;
  background:#0092ff;
  margin-top:100px;
}
.positioned1 {
  position:absolute;
  top:75%;
  left:75%;
  bottom:-3em;
  right:-3em;
  background:#FFA500; 
}
<div class="container">
   box1
   <div class="positioned"></div>
</div>
<div class="container1">
  box2
  <div class="positioned1"></div>
</div>

您需要清除第二个 div (".container1") 的浮动。

示例:

   .container {
        position: relative;
        width: 10em;
        height: 10em;
        background: #aaa;
        float: left;
    }

    .container1 {
        position: relative;
        width: 10em;
        height: 10em;
        background: #aaa;
        clear: both;
    }

根据您的目标,这里有两种不同的解决方案:

  1. 如果您愿意将两个容器分开放在不同的行中,您需要将 clear: both 属性 添加到 <div class="container1"> 这样它就不会向左或向右附加表格floating内容。

.container {
  position:relative;
  width:10em;
  height:10em;
  background:#aaa;
  float:left;
}
.positioned {
  position:absolute;
  top:50%;
  left:50%;
  bottom:0;
  right:0;
  background:#FFA500; 
}
.container1 {
  position:relative;
  width:10em;
  height:10em;
  background:#0092ff;
  margin-top:100px;
  clear: both; /*Add this property*/
}
.positioned1 {
  position:absolute;
  top:75%;
  left:75%;
  bottom:-3em;
  right:-3em;
  background:#FFA500; 
}
<div class="container">
   box1
   <div class="positioned"></div>
</div>
<div class="container1">
  box2
  <div class="positioned1"></div>
</div>

  1. 如果您愿意将两个容器放在同一条线上而不是彼此重叠,您也需要给 <div class="container1"> 一个 float 属性。

.container {
  position:relative;
  width:10em;
  height:10em;
  background:#aaa;
  float:left;
}
.positioned {
  position:absolute;
  top:50%;
  left:50%;
  bottom:0;
  right:0;
  background:#FFA500; 
}
.container1 {
  position:relative;
  width:10em;
  height:10em;
  background:#0092ff;
  /*margin-top:100px;*/ /* Margin top removed to give both containers same height */
  float: left; /* Add this property */
}
.positioned1 {
  position:absolute;
  top:75%;
  left:75%;
  bottom:-3em;
  right:-3em;
  background:#FFA500; 
}
<div class="container">
   box1
   <div class="positioned"></div>
</div>
<div class="container1">
  box2
  <div class="positioned1"></div>
</div>