2012-01-30 40 views
47

我在同一行上有兩個元素向左浮動並右移。如何在不更改HTML的情況下在同一行上對齊兩個元素

<style type="text/css"> 
#element1 {float:left;} 
#element2 {float:right;} 
</style> 

<div id="element1"> 
element 1 markup 
</div> 
<div id="element2"> 
element 2 markup 
</div> 

我需要element2排列在element1旁邊,在兩者之間填充大約10個像素。問題是元素2的寬度可能會根據內容和瀏覽器(字體大小等)而變化,所以它不總是與元素1完美地排列在一起(我不能僅僅應用邊距並將其移過)。

我也無法更改標記。

有沒有統一的方法來排列它們?我嘗試了一個百分比的margin-right,我在element1上嘗試了一個負邊距,以使element2更接近(但無法讓它工作)。

+0

將元素#2的左邊和左邊的元素左右浮動都出現了什麼問題? – 2012-01-30 17:23:38

+0

他們有沒有固定的或流體的寬度? – Alexander 2012-01-30 17:25:37

回答

102

使用display:inline-block

#element1 {display:inline-block;margin-right:10px;} 
#element2 {display:inline-block;} 

Example

15
#element1 {float:left;} 
#element2 {padding-left : 20px; float:left;} 

小提琴:http://jsfiddle.net/sKqZJ/

#element1 {float:left;} 
#element2 {margin-left : 20px;float:left;} 

撥弄:http://jsfiddle.net/sKqZJ/1/

#element1 {padding-right : 20px; float:left;} 
#element2 {float:left;} 

撥弄:http://jsfiddle.net/sKqZJ/2/

#element1 {margin-right : 20px; float:left;} 
#element2 {float:left;} 

撥弄:http://jsfiddle.net/sKqZJ/3/

參考:The Difference Between CSS Margins and Padding

2

在我使用浮動元素這樣的情況下,我通常需要確保容器元素永遠是足夠大了兩者的寬度浮動元素加上所需的邊距,以使其適合所有元素。要做到這一點,最簡單的辦法顯然是既提供內部元件固定寬度,將正確地安裝這樣的外部件的內部:

#container {width: 960px;} 
#element1 {float:left; width:745px; margin-right:15px;} 
#element2 {float:right; width:200px;} 

如果你不能這樣做,因爲這是一個縮放寬度的佈局,另選擇是讓每一套尺寸是百分比,如:

#element1 {float:left; width:70%; margin-right:10%} 
#element2 {float:right; width:20%;} 

這得到棘手,你需要這樣的事:

#element1 {float:left; width:70%; margin-right:10%} 
#element2 {float:right; width:200px;} 

在這樣的情況下,我覺得日在有時最好的選擇是不使用花車,並使用相對/絕對定位得到這樣的效果相同:

#container {position:relative;} /* So IE won't bork the absolute positioning of #element2 */ 
#element1 {margin-right:215px;} 
#element2 {display: block; position:absolute; top:0; right:0; height:100%; width:200px;} 

雖然這不是一個浮動的解決方案,它通過側欄,其中導致副他們是相同的高度,一個可以保持流暢而另一個具有靜態寬度。

0

通過使用display:inline-block;更一般地,當你有一個父母(總是有一個父母除了HTML)使用display: inline-block;作爲內部元素。並強制他們留在同一行,即使窗口縮小(合同)。添加父兩個屬性:

white-space: nowrap; 
    overflow-x: auto; 

這裏更多格式例如要清楚:

.parent { 
    white-space: nowrap; 
    overflow-x: auto; 
} 

.children { 
    display: inline-block; 
    margin-left: 20px; 
} 

在這個例子中特別是,你可以申請上述老鄉(我假設的父母是身體,如果不是你把正確的父母),你也可以像更改HTML併爲他們添加一個父母如果可能的話。

body { /*body may pose problem depend on you context, there is no better then have a specific parent*/ 
     white-space: nowrap; 
     overflow-x: auto; 
} 

#element1, #element2{ /*you can like put each one separately, if the margin for the first element is not wanted*/ 
    display: inline-block; 
    margin-left: 10px; 
} 

記住white-space: nowrap;overlow-x: auto;是你需要迫使他們在一條線的。白色空間:nowrap;禁用包裝。而overlow-x:auto;當元素超過幀限制時激活滾動。

相關問題