Div不会向左浮动

时间:2016-09-30 05:17:15

标签: html css html5

我已将图片添加到我的div中,并使用position:absolute的图片来定位我输入的块。但当我float它离开时,它会在图片上显示,但它不会向左浮动。它只是留在另一个后面。如何在不使用position: relative

的情况下使其向左浮动

代码:

#knowledge-div {
  height: 50%;
  width: 100%;
  width: 0 auto;
}
#knowledge-div img {
  height: 100%;
  width: 100%;
  float: left;
}
.blocks {
  width: 498px;
  height: 50%;
  float: left;
  position: absolute;
}
#green {
  background-color: green;
}
#orange {
  background-color: orange;
}
<div id="knowledge-div">
  <img src="Pictures/biganswer.jpg">
  <div class="blocks" id="green"></div>
  <div class="blocks" id="orange"></div>
</div>

3 个答案:

答案 0 :(得分:1)

#knowledge-div {
  height: 50%;
  width: 100%;
  width: 0 auto;
}
#knowledge-div img {
  height: 100%;
  width: 100%;
  float: left;
}
.blocks {
  width: 498px;
  height: 50%;
float:left;
}
#green {
  background-color: green;
}
#orange {
      background-color: orange;
}

<div id="knowledge-div">
  <img src="Pictures/biganswer.jpg">
  <div id="green" class="blocks" >Color green</div>
  <div class="blocks" id="orange">Color orange</div>
</div>

No need to define position property in blocks class. Add some text in div for both colors.

答案 1 :(得分:0)

当你想浮动元素时,你不应该使用position:absolute。

尝试这样的事情:

#knowledge-div {
  height: 50%;
  width: 100%;
  width: 0 auto;
}
#knowledge-div img {
  height: 100%;
  width: 100%;
  float: left;
}
.blocks {
  width: 50%;
  height: 50%;
  float: left;
  clear: none;
  color: red;
}
<div id="knowledge-div" style="height:100px; background-image:url('https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png'); background-color: #cccccc;">

  <div class="blocks" id="green" >Green</div>
  <div class="blocks" id="orange">Orange</div>
  <div style="float:left; clear:both"></div>
</div>

答案 2 :(得分:0)

绝对定义的元素的位置不会改变,除非你使它相对,否则定义填充或边距。当您尝试移动元素并且没有足够的空间驻留时,它会移动相邻元素。