Div应该是其子女的宽度,而另一个孩子应该包裹

时间:2014-09-19 08:58:28

标签: html css

我有一个容纳一些动态内容的简单容器。看起来应该是这样的:

--------------------     -------------------------------
| This is the title |    | This is a much longer title |
--------------------     -------------------------------
| This is the text  |    | This is the text that will  |
| that will be put  |    | be put onto multiple lines  |
| onto multiple     |    | depending on the width of   |
| lines depending   |    | the title                   |
| on the width of   |    -------------------------------
| the title         |
--------------------

我想"这是标题"设置容器的宽度,使其始终在一行上。另一个文本应该换行多行。

JSFiddle显示问题。

3 个答案:

答案 0 :(得分:1)

这有效 - http://jsfiddle.net/945n1ofs/

inline-block上的.container使其尽可能地缩小,然后white-space: nowrap上的.title强制它变得尽可能宽。< / p>

然后,.container位于.content内且相对定位absolute意味着.content不能影响.container的宽度它不在文件流程之内。

最后,您只需要为孩子添加一个top位置来计算单行标题,并将边框移到标题和子项上。

答案 1 :(得分:0)

理查德,

你必须添加一些javascript

的Javascript

还包括来自Here

的JQuery文件
$(document).ready(function () {
    var x = $('.title').outerWidth(true); // Find width of TITLE
    $('.content').attr("style", "width:"+ x +"px"); // Assign the TITLE value to CONTENT
});

CSS

.container {
    border: 1px solid black
}

.title {
    border-bottom: 1px solid black;
    display:inline-block;
}

答案 2 :(得分:0)

我不确定你是否可以用纯CSS实现这一点。但是在JS的帮助下,它可以是这样的:

CSS

.container {
    border: 1px solid black;
    display: inline-block;
}
.title {
    float: left;
    border-bottom: 1px solid black;
}
.content {
    clear: both;
}

JS

$(document).ready(function () {
   var titleWidth = $('.title').width();
   $('.title').next('.content').width(titleWidth);
});