浮动元素进入下一个框

时间:2016-06-02 07:07:20

标签: css css-float

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

点击这里的小提琴: 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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

根据您的目标,您可以在此处找到两种不同的解决方案:

  1. 如果您愿意将不同行中的两个容器分开,则需要将clear: both属性添加到<div class="container1">,以便它不会向左或向右附加表单floating } content。
  2. &#13;
    &#13;
    .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; 
    }
    &#13;
    <div class="container">
       box1
       <div class="positioned"></div>
    </div>
    <div class="container1">
      box2
      <div class="positioned1"></div>
    </div>
    &#13;
    &#13;
    &#13;

    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; }属性。
    2. &#13;
      &#13;
      <div class="container">
         box1
         <div class="positioned"></div>
      </div>
      <div class="container1">
        box2
        <div class="positioned1"></div>
      </div>
      &#13;
      Example.exampleid = SLA.exampleId.
      
      &#13;
      &#13;
      &#13;

答案 1 :(得分:0)

您需要清除第二个div(&#34; .container1&#34;)的浮动。

示例:

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

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