根据前一个跨度的宽度将动态宽度设置为div

时间:2014-01-16 15:58:35

标签: html css

我有两个要素;即一个跨度,然后一个div。跨度的内容应该具有长度为25到30个字符的最大值,并且div的内容可以是段落(并且两个内容都是动态的)。我的客户想要的是设置div的宽度与跨度的宽度相同(没有高度问题)。现在我用JS实现了这个并且工作正常,我们可以用CSS做同样的事情,这样我的生活会更容易吗?

感谢您的回复。

Tismon Varghese。

编辑:请参阅以下代码

<div class="wrapper">
<span class="summary-headder"> Header Header Header Header Header </span>
<div class="summary-comment" style="width: 495px;">
    test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment test comment          
</div>
</div>

var summary_headder_width  = $('.summary-headder').width();

$('.summary-comment').css('width', summary_headder_width + 'px');

3 个答案:

答案 0 :(得分:0)

<div style="display: table">
   <span style="display: table-row">Test text test text test text</span>
   <div style="display: table-row; border: 1px solid black; width: 100%; float: left">test</div>
</div>

http://jsfiddle.net/Xg8eT/

答案 1 :(得分:0)

这样做的方法是将您的包装器显示为固定的1px宽度(宽度:1px;)的表格(display:table;),并在此宽度上方加上带有white-space:nowrap的标题。下面的div,不是覆盖宽度,将遵循其sibbling宽度。

div.wrapper {
    display:table;
    width:1px;
}

span.summary-header {
    display:table-row;
    background-color:green;
    white-space:nowrap;
}

div.summary-comment {
    display:table-row;
    background-color:blue;
}

请参阅此Fiddle以获取合适的解决方案。

答案 2 :(得分:0)

您可以使用表格来完成 http://jsfiddle.net/zNJ34/1/

<table>
    <tr>
        <th>Header Header Header Header Header</th>
    </tr>
    <tr>
        <td>test comment test comment test comment test comment test comment test comment</td>
    </tr>
</table>