为什么非浮动容器中的文本识别相邻浮动容器的宽度?

时间:2016-05-11 12:49:09

标签: css

我从类float:right;中删除了.floated_rightdiv按预期行事,它忽略了.floated_left div的宽度并从最左边开始。

为什么文本会识别.floated_left div的宽度?我希望它从容器的最左边开始。



.floated_left {
  float: left;
  width: 200px;
  border: 1px solid red;
}
.floated_right {
  width: 600px;
  border: 3px solid blue;
  /*float:right;*/
}

<div class="floated_left">
  This
  <br />is
  <br />just
  <br />a
  <br />left
  <br />floated
  <br />column
  <br />
</div>
<div class="floated_right">
  Why
  <br />the
  <br />text
  <br />appears
  <br />here
  <br />not
  <br />left blue border?
  <br />
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:2)

原因是,浮动元素占据浮动空间,其余部分留在左侧。如果您希望新<div>从左边框占用空间,则需要:

  • clear: left用于新<div>
  • 使用display: inline-block;作为原始<div>

enter image description here

案例1:使用clear: left

.floated_left {
  float: left;
  width: 200px;
  border: 1px solid red;
}
.floated_right {
  width: 600px;
  border: 3px solid blue;
  clear: left;
}
<div class="floated_left">
  This
  <br />is
  <br />just
  <br />a
  <br />left
  <br />floated
  <br />column
  <br />
</div>
<div class="floated_right">
  Why
  <br />the
  <br />text
  <br />appears
  <br />here
  <br />not
  <br />left blue border?
  <br />
</div>

案例2:使用display: inline-block;

.floated_left {
  display: inline-block;
  width: 200px;
  border: 1px solid red;
}
.floated_right {
  width: 600px;
  border: 3px solid blue;
}
<div class="floated_left">
  This
  <br />is
  <br />just
  <br />a
  <br />left
  <br />floated
  <br />column
  <br />
</div>
<div class="floated_right">
  Why
  <br />the
  <br />text
  <br />appears
  <br />here
  <br />not
  <br />left blue border?
  <br />
</div>

预览

enter image description here