css - float 元素进入下一个框

标签 css css-float

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

检查这里的 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>

最佳答案

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

  1. 如果您愿意将两个容器分开放在不同的行中,您需要添加 clear: both属性(property)<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也是属性(property)。

.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>

关于css - float 元素进入下一个框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37584902/

相关文章:

jquery - 如何停止在 Google Chrome 中 div 内 float 右图像溢出

html - 使登录链接与其他链接对齐

html - CSS Box/shadow 重叠问题 z-index

CSS 在使用 float :left; 时摆脱额外的间距

css - google webfonts 在 chrome 上看起来很糟糕

jquery - 溢出:隐藏属性在 Firefox 中表现异常/在 Chrome/Safari 中表现良好

jquery - Bootstrap 3.x : display:none for accordion

css - 我的 div 不会向左或向右浮动?

与 ThemeRoller 提供的完全不同的 jQuery UI 主题

javascript - 向下滚动时标题褪色 - 也适用于向上滚动