2012-08-03 91 views
4

我有一個基本的兩列CSS佈局,CSS看起來像CSS 2列布局

#sidebar { 
    width:100px; 
} 
#main { 
    margin-left:100px; 
} 

和一些示例HTML

<div id="content"> 
    <div id="sidebar">some sidebar content</div> 
    <div id="main">some main content</div> 
</div> 

這工作,但似乎重複和容易出錯的邊欄寬度需要與主邊距左邊的值相匹配。有一個更好的方法嗎?

回答

6

可以使用上#sidebarfloat屬性:

#sidebar { 
    width:100px; 
    float: left; 
} 

JS Fiddle Example


然而,使用上述方法,如果#main含量導致其高度延伸下面#sidebarit will wrap under the sidebar。爲了避免這種情況,可以使用display:table-cell屬性:

#sidebar, #main { 
    display: table-cell; 
} 

JS Fiddle Example

+0

如果主要內容比側邊欄內容更長並且換行,換行似乎最終會在側邊欄下... – 2012-08-03 15:32:12

+0

@JeffStorey。嘗試在'#sidebar'和'#main'中添加'display:table-cell':http://jsfiddle.net/HTqHJ/2/ – JSW189 2012-08-03 15:35:01

+0

這樣做,謝謝 – 2012-08-03 15:36:38

2

CSS

#sidebar { width:100px; float: left; } 
#main { float: right; } 

HTML

<div id="content"> 
    <div id="sidebar">my stuff</div> 
    <div id="main">some main content</div> 
    <div style="clear:both;"></div> 
</div> 

我建議960.gsBlueprintCSS基本-HTML/CSS樣式。

+0

當我把浮動:留在主,他們都似乎左對齊... – 2012-08-03 15:30:15

+0

哦 - 是的。只是'漂浮:正確';' J4I:也許你應該看看960gs(http://www.960.gs)或BlueprintCSS(http://www.blueprintcss.org)。 – Thomas 2012-08-03 15:32:11

+0

謝謝。它看起來像使用顯示:表格單元格由@ JSW189建議,因爲我期望 – 2012-08-03 15:38:41

0

您可以嵌套sidebarmain給人留下main填充和sidebar一個-ve保證金。

#content{ 
    width: 100%; 
} 
#sidebar, #main{ 
    float: left; 
    display: block; 
} 
#sidebar{ 
    width: 100px; 
    background-color: orange; 
    margin-left: -100px; 
} 
#main{ 
    padding-left: 100px; 
    background-color: green; 
    width: 100%; 
} 

<div id="content"> 
    <div id="main"> 
     <div id="sidebar">some sidebar content</div>some main content 
    </div> 
</div> 

Here是工作演示。