簡體   English   中英

CSS中的浮動 - 浮動到右邊時,空隙/空間留在頂部?

[英]Floats in CSS - Gap/space left on top when floated to the right?

這有點難以描述,但基本上我的頁面上浮動的div留下了不受歡迎的空間。 這是描述問題的圖片。 黑匣子是div。

浮動之前:

替代文字

浮動后:

替代文字

期望的效果:

替代文字

而且我不確定它是否有所作為,但我也有一個空的div,其中“clear:both”立即放置在浮動的div之后。

我怎樣才能做到這一點?

如果可能的話,在HTML中的unfloated div之前放置float: right div

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
}

刪除清除div。 還要檢查這些div上的填充/邊距,並確保包含div(父div)足夠寬以容納兩個子div。

<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;
}

=======嘗試這個

第一個div應該有float: left set。 否則,第一個div(塊元素)將占用所有垂直空間。

浮標存在空白問題。 這就是為什么第二個盒子略低。

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

將工作。

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

不行

問題是你只浮動一個div。 您需要使非foated div上的margin-right與浮動div的總空間(width + paddding + 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>

兩個div應向左浮動,並確保它們等於或小於它們所在容器的寬度。

如果a1要顯示浮動到a2的右邊,那么你必須在html中放置a1 FIRST,並將其向右浮動。 有點反直覺,但它的浮動工作方式。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM