【问题标题】:auto adjusted 2 div depending on the content根据内容自动调整 2 div
【发布时间】:2011-08-18 18:52:09
【问题描述】:

我需要编写 CSS 来调整包含在固定大小的 div 中的 2 列 div

<div style="width:500px">
<div id="description" class="col1">
</div>
<div id="price" class="col2">
</div>
</div>

.col1
{
float: left;
clear: left;
}
.col2
{
text-align: right;
float: right;
max-width: 150px; 
}

我为 col2 设置了最大宽度,我想要以下行为。

  • col1 的内容是可变的,col2 的内容也是可变的。
  • 如果 col2 的内容小于 150px 宽度,则 col1 必须占据剩余的位置。
  • 如果 col2 的内容超过 150px 宽度,col2 将被限制为 150px 宽度,col1 被限制为 350px。

问题是 col1 的内容宽度超出了可用空间,col1 将占用所有容器宽度(500px)。 col2 将在 col1 之后垂直移动。

【问题讨论】:

    标签: css css-float


    【解决方案1】:

    你的要求一开始让我很困惑,但现在再看一遍,这很有道理。

    见:http://jsfiddle.net/thirtydot/SJg4M/

    HTML:

    <div class="colContainer">
        <div id="price" class="col2">price</div>
        <div id="description" class="col1">description</div>
    </div>
    

    如您所见,我不得不交换#price#description 的顺序。我希望这是可以接受的。

    CSS:

    .colContainer {
        width: 500px;
        overflow: hidden;
        background: #ccc
    }
    .col1 {
        overflow: hidden;
        background: #f0f
    }
    .col2 {
        text-align: right;
        float: right;
        max-width: 150px; 
        background: #999
    }
    

    【讨论】:

    • 太棒了!这正是我一直在寻找的
    【解决方案2】:

    只需为.col1 添加一个最大宽度。如果你的容器 div 是 500px,那么

    这是我能想到的最好的方法,使用 javascript 将 col1 的宽度设置为 500px 容器和 col2 宽度之间的差异。

    var width = 500 - $('#price').width();
    $('#description').css('width', width+'px');
    

    示例:http://jsfiddle.net/JZLBN/

    【讨论】:

    • 这不是我想要的。如果我把 max-width:350px 放到 col1.例如 col2 为 100px,col1 将不会使用 50px 的间隙。
    • 我唯一能想到的就是使用javascript将col1的宽度设置为500与col2的宽度之差。也许更聪明的人可以给你一个 CSS 答案。用 jquery 代码编辑了我的答案。
    【解决方案3】:

    我没有 redy 解决方案,但是我的想法是尝试各种显示:例如 XX 属性

      display: table-row
    

    等等。不过我还没有测试过,我很好奇这是否能解决问题:) IE7 不支持它,所以如果你需要它,请跳过我的建议。这不是一个真正的答案,很乐意阅读 cmets 关于这个想法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-11
      • 2012-04-23
      • 1970-01-01
      • 2015-02-23
      • 2011-09-15
      相关资源
      最近更新 更多