2011-03-14 75 views
2

問題:在下面的HTML的標記:CSS:如何實現 - 將兩個元素並排放置並且沒有第三個父容器並排放置?

<html> 
    <body> 
    <div id="div_1"></div> 
    <div id="div_2"></div> 
    </body> 
</html> 

我希望同時div的(這可以是任何其他標記)爲中心並位於側由端。如何用CSS實現這一點,而不需要添加第三個父容器?

+0

所以,你已經解決了這個?下面的答案似乎乍一看起作用。 – thirtydot 2011-03-14 15:17:55

回答

5

演示在這裏:http://jsfiddle.net/Shehi/6RqWb/

以下CSS規則解決的問題:

#div_1 
{ 
    width: 200px; 
    height: 200px; 
    background-color: red; 
    position: relative; 
    left: 50%; 
    margin-left: -200px; /* = -1 * the width of element */ 
    float: left; 
    clear: none; 
} 

#div_2 
{ 
    width: 200px; 
    height: 200px; 
    background-color: blue; 
    position: relative; 
    right: 50%; 
    margin-right: -200px; /* = -1 * the width of element */ 
    float: right; 
    clear: none; 
} 
+0

+1,但我很好奇:沒有;你能解釋一下嗎? – Dave 2011-03-14 15:18:02

+0

'clear:none'在這裏完全沒有做什麼。 – thirtydot 2011-03-14 15:18:58

+0

大聲笑...我剛剛從我自己的代碼中複製,所以忘了從答案中刪除'clear:none;'部分...對不起:)但是,添加'clear:left'和'clear:right'到那些元素將確保他們是唯一的行中。 – 2011-03-14 15:28:25