【问题标题】:Two column layout with one having a fixed width in CSS两列布局,其中一列在 CSS 中具有固定宽度
【发布时间】:2010-09-13 17:58:40
【问题描述】:

我想要一个使用 CSS 浮动的漂亮的 2 列布局。

列#1 160 像素 第 2 列 100%(即剩余空间)。

我想先放置 Col#2 的 div,所以我的布局如下:

<div id="header"></div>
<div id="content">
     <div id="col2"></div>
     <div id="col1"></div>
</div>
<div id="footer"></div>

要达到这个效果需要什么?

【问题讨论】:

    标签: css layout


    【解决方案1】:

    以上都行不通。

    div#col2 {
        width: 160px;
        float: left;
        position: relative;
    }
    
    div#col1 {
        width:100%;
        margin-left: 160px;
    }
    

    假设第 2 列应显示为左侧边栏,第 1 列作为主要内容。

    【讨论】:

    • 我认为情况正好相反。
    • 请记住,当您提及其他问题时,它们不是“上方”或下方,因为当它们收集选票时,问题的顺序会发生变化。使用答案中的引用,或完全避免使用措辞:如果你说的“鲍勃的答案”很好,他们可能会在你之后再回答。
    • 这是答案,但mabwi需要交换#col1 #col2。投了赞成票以期待更正。
    【解决方案2】:

    您应该使用“float”CSS 属性来执行此操作。查看simple implementation here。你可以找到更详细的article here

    【讨论】:

      【解决方案3】:

      您必须在第一列使用 float:left 并在第二列使用 float:right

      【讨论】:

        【解决方案4】:

        我认为你可以这样做。

        div#col2 {
          padding-left: 160px;
          width: 100%;
        }
        
        div#col1 {
          float: left;
          width: 160px;
        }
        

        这依赖于 #col1#col2 之前出现,这可能会使其无法使用。

        这不会,但取决于 #col1 是否更长:

        #content {
          position: relative;   
        }
        div#col2 {
          width: 160px;
          position: absolute;
        }
        
        div#col1 {
          width: 100%;
          margin-left: 160px;
        }
        

        这将使页脚保持在原位。

        div#footer {
          clear: both;
        }
        

        【讨论】:

          【解决方案5】:

          虽然这个问题是多年前的问题,但我为任何未来的参考和类似案例提供了这个有用的答案。

          在标记中将#col1 放在#col2 之前,您可以将其浮动到右侧,以防您有LTR lauout(如果您有RTL 布局则浮动到左侧)并给出另一个列overflow: hidden

          请注意,父级 (#content) 也应该有 overflow: hidden

          #content{
            overflow: hidden;
            padding: 20px 0;
            height: 100px;
            background-color: #cdeecd;
          }
          
          #content #col1{
            float: right;
            width: 160px;
            height: 100px;
            background-color: #eecdcd;
          }
          
          #content #col2{
            height: 100px;
            overflow: hidden;
            background-color: #cdcdee;
          }
          <div id="content">
               <div id="col1"></div>
               <div id="col2"></div>
          </div>

          【讨论】:

            猜你喜欢
            • 2020-11-30
            • 2011-10-02
            • 1970-01-01
            • 2023-03-18
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多