【问题标题】:css 2 column layoutcss 2列布局
【发布时间】:2012-08-03 23:40:13
【问题描述】:

我有一个基本的两列 CSS 布局,CSS 看起来像

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

这可行,但侧边栏宽度需要与主边距左值匹配似乎重复且容易出错。有没有更好的方法来做到这一点?

【问题讨论】:

    标签: css layout


    【解决方案1】:

    您可以在#sidebar 上使用float 属性:

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

    JS Fiddle Example


    但是,使用上述方法,如果#main的内容导致其高度延伸到#sidebar以下,it will wrap under the sidebar。为避免这种情况,请使用display:table-cell 属性:

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

    JS Fiddle Example

    【讨论】:

    • 如果主要内容长于侧边栏内容并换行,则换行似乎最终在侧边栏下方...
    • @JeffStorey。尝试将display:table-cell 添加到#sidebar#mainjsfiddle.net/HTqHJ/2
    【解决方案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 样式。

    【讨论】:

    • 哦 - 没错。只是'浮动:对;' J4I:也许你应该看看 960gs (960.gs) 或 BlueprintCSS (blueprintcss.org)。
    • 谢谢。它看起来像使用 @JSW189 建议的 display:table-cell ,正如我所期望的那样布局
    • ic - 无论如何你应该看看提到的 css-frameworks。它们易于使用和理解。
    【解决方案3】:

    您可以将sidebar 嵌套在main 中,给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 是工作演示。

    【讨论】:

      猜你喜欢
      • 2016-10-31
      • 1970-01-01
      • 2016-07-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多