CSS中的浮动——向右浮动时顶部留下间隔/空白?

5
这个有点难描述,但基本上我的页面上有一个浮动的div会留下不必要的空白。以下是描述问题的图片。黑色方框是div。
浮动之前: alt text 浮动之后: alt text 期望效果: alt text 我不确定这是否有影响,但是我还放了一个带“clear:both”的空div在浮动的div之后。
如何实现这个效果?

2
我们能看到导致这个问题的CSS和HTML吗? - Sean Vieira
我尝试将两个div都浮动起来,但这并没有立即解决我的问题。问题在于有一个流氓div(未浮动)悬挂在中间,仍然导致与上述相同的效果。将此div移动到最左边的div内部后,我能够实现正确的效果。下面标记的答案是帮助我解决问题的答案。感谢大家的回答。 - ground5hark
9个回答

8
如果可能的话,请在HTML中将float:right
放在未浮动的
之前。

3
<div class="a1">a1</div>
<div class="a2">a2</div>

.a1
{
 background-color:Red;
  width:200px;
  height:200px;
float:left; 
}
.a2
{
  background-color:Green;
  width:200px;
  height:200px;
  float:left;
}

=======尝试这个


3
HTML
<div id="container">
   <div id="main">
     blah blah blah blah blah
   </div>
   <div id="aside">
   this goes to the side
   </div>
   <div id="clear"></div>
</div>

CSS
div#container
{
    width : 80%;//your preference
    height : auto;
    margin : 0 auto;//Centers the page
}

div#main
{
    width : 70%;
    height : auto;
    display : block;//to wrap it up inside its width
    float : left;//float it towards left
}

div#aside
{
    width : 30%;//take up rest of the width size
    height : auto;
    display : block;
    float :right;//float towards right
}

#clear
{
    clear : both;//this will do the job
}

3

删除clearing div。同时检查这些div的padding / margin,并确保包含div(父div)足够宽以容纳两个子div。


3
第一个 div 应该设置为 float: left。否则第一个块级元素的垂直空间将全部占用。

0
问题在于你仅对一个 div 进行了浮动。你需要将非浮动 div 的 margin-right 设置为与浮动 div 的总空间宽度(width+padding+margin)相同。
或者,您可以同时浮动两个 div。
示例:
<div id="container" style="width: 410px;">
<div style="float: right; width: 200px;">
  <p> Right div</p>
</div>
<div style="width: 200px; margin-right: 210px;">
  <p> Left Div</p>
</div>
<div style="clear:both;"></div>
</div>

或者:

<div id="container" style="width: 410px;">

<div style="float: left; width: 200px; margin-right: 10px;">
  <p> Left Div</p>
</div>
<div style="float: left; width: 200px;">
  <p> Right div</p>
</div>
<div style="clear:both;"></div>
</div>

0
如果要让a1浮动到a2右侧,就得先把a1放在HTML中并向右浮动。这有点违反直觉,但这就是浮动的工作方式。
<div class="container">
  <div class="a1">a1</div>
  <div class="a2">a2</div>
</div>
<style>
div
{
  border: solid 2px #000;
  background-color: #eee;
}
.a1
{
 background-color:Red;
  width:200px;
  height:200px;
float:right; /* the trick is, a1 appears BEFORE a2 in the html, yet
we are floating a1 right .  if you do it the other way around
( try and float a2 ) then it will work like you showed
(separate line)*/
}
.a2
{
  background-color:Green;
  width:200px;
  height:200px;
  /* don't float this one */

}
</style>

0

浮动元素存在空白间隙问题,这就是为什么第二个框稍微低一些的原因。

<div style="float:left">a1</div><div style="float:left">a2</div>

会起作用。

<div style="float:left">a1</div>
<div style="float:left">a2</div> 

无法工作


0

两个 div 元素应该向左浮动,并确保它们的宽度等于或小于它们所在容器的宽度。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接