2列布局流体可调宽度

时间:2014-07-25 13:39:07

标签: html css

我已经搜索了几天的解决方案,现在似乎无法找到答案。我想要实现的是一个2列布局,其中左列基于浏览器宽度和基于其内容的右列宽度是流动的。

右列不能具有固定宽度,因为某些内容是从数据库生成的,宽度可能会有所不同。我认为该解决方案有一些处理显示:内联块但似乎无法正确。当左列的内容推动列的宽度大于可用空间时,右列跳转到另一行并且不保持内联。

我们还需要远离任何javascript,因为有些用户会禁用它。

非常感谢任何帮助!

enter image description here

这是我到目前为止所做的:

HTML:

<div id='container'>
   <div id='left'> 
      this is some really long text that takes up a lot of room since it is so long
   </div>
   <div id='right'>
      <a>this is a link</a>
   </div>
</div>

CSS:

#container{
   width: 100%;
   background: red;
}

#left{
   display: inline-block;
   background: green;
}

#right{
   display: inline-block;
   margin: 15px;
   background: yellow;
}

#right a{
   padding: 5px 20px;
}}

2 个答案:

答案 0 :(得分:0)

您可以尝试使用flexbox:

http://css-tricks.com/snippets/css/a-guide-to-flexbox/

这是非常好的工具。我想它可能有所帮助。

答案 1 :(得分:0)

在研究答案后,我实际上遇到了一些代码并注意到一个可能的答案似乎有效!我的原始代码非常接近,但显示错误:内联块是关键。答案实际上是CSS的一个小变化,但最重要的是我的HTML的顺序。

答案是在左侧放置右栏 BEFORE 。通过这种方式,浏览器可以计算出它认为的是什么&#34;剩余的&#34;左列的宽度,但我们向后显示它。换句话说,我们首先将列布置在右边,然后根据子节点的宽度计算,然后让浏览器计算左列宽度的其余部分。然后在CSS中我们切换左右列的位置以显示我们想要的方式。

以下是工作代码:

CSS:

    html,
    body{
        height: 100%;
    }

    #container{
        width: 100%;
        min-height: 100%;
        height: 100%;
        background: red;
    }

    #left{
        width: auto;
        background: green;
    }

    #rightWrapper{
        float: right;
        height: 100%;
        background: blue;
    }

    #right{
        margin: 15px;
        background: yellow;
    }

    #right a{
        padding: 5px 20px;
    }

HTML:

    <div id='container'>
       <div id='rightWrapper'>
           <div id='right'>
              <a>this is a link that grows</a>
           </div>
       </div>
       <div id='left'>
          this is some really long text that takes up a lot of room since it is so long ........
       </div>
   </div>

<强>更新 在处理完全不同的问题时,偶然发现这个解决方案不那么复杂。基本上只需将外部转换为表格,将内部转换为表格单元格。如果没有给出高度,则假设全高,并将列宽设置为小于您需要的值。这是一个示例:

CSS:

    #container{
        width: 100%;
        display: table;
        background: red;
    }

    #left{
        display: table-cell;
        background: green;
    }

    #right{
        display: table-cell;
        width: 50px;
        background: yellow;
    }

    #right a{
        padding: 5px 20px;
    }

HTML:

    <div id='container'>
       <div id='left'>
          this is some really long text that takes up a lot of room since it is so long ........
       </div>
       <div id='right'>
          <a>this is a link that grows</a>
       </div>
   </div>