我想将 div宽度等于内容最长的单词/句子长度。这是样本:
<div id="1">I_want_to_make_div_width_equal_to_this_word</div>
使用此css代码可以正常工作:
div {display: inline-block;}
它也适用于此示例:
<div id="2"> I_want_to_make_div_width_equal_to_this_word <br/>
and_anther_word_in_next_line </div>
Div = id =&#34; 2&#34;宽度是最长的单词。
但我的问题是这个例子。当内容窗口太小而不能在一行中包含两个单词时,div的宽度为100%窗口大小:
<div id="3"> I_want_to_make_div_width_equal_to_this_word
and_anther_word_in_next_line </div>
id = 3的div是否可能表现得像id = 2但没有<br />
符号?
我刚刚描述的例子:http://jsfiddle.net/2vffqrwy/(使窗口的宽度将第三个div中的单词分成两行。)
编辑: 完美的解决方案是当div id = 3时,当窗口足够大时,在一行中显示两个单词,当窗口小到一行时,行为就像div id = 2。
答案 0 :(得分:2)
我能看到解决这个问题的唯一方法是使用javascript,
我做了一个uggly,可能是过度的技巧片段来完成工作:
它创建节点的克隆,使用inline
将其设置为white-space: nowrap
,然后一次添加一个单词,将克隆宽度与父宽度进行比较。如果它更大,则会将display: table-caption
分配给原始div,否则会添加下一个单词。
<强> CSS 强>
div {
display: inline-block;
background-color:pink;
margin-bottom:5px;
}
.caption {
display : table-caption;
}
.cloned {
visibility : hidden;
white-space : nowrap;
}
<强>的Javascript 强>
var clone, el,w;
(cloneIt)();
function cloneIt(){
el = document.getElementById('3');
clone = el.cloneNode(true);
clone.className = "cloned";
el.parentNode.appendChild(clone);
w = clone.innerHTML.split(' ');
wrapIt();
}
window.onresize = wrapIt;
function wrapIt(){
clone.innerHTML = w[0]; //minimum content is first word
for(i=1; i<w.length; i++){
clone.innerHTML += w[i]+' ';//add next word
if(i==w.length-1 && clone.offsetWidth <= el.parentNode.offsetWidth){
//we're at the end and it's still smaller than parent width?
el.style.width = clone.offsetWidth+ 1 + 'px';
return;
}
if(clone.offsetWidth <= el.parentNode.offsetWidth){
//add a new word
continue;
}
//Gone too far? remove last word
clone.innerHTML = clone.innerHTML.replace(w[i], '');
el.style.width = clone.offsetWidth+ 1 + 'px';
return;
}
}
答案 1 :(得分:0)
您必须为div设置宽度,或者您可以将文本放在<p></p>
标记内,并在CSS上设置段落的宽度。
示例:
#3 {
width: 300px;
}
或者,如果你想要更具语义的东西:
#3 p {
width: 300px;
}
答案 2 :(得分:0)
实际上,如果不将元素包裹在例如span或div之类的东西上,就不可能创建换行符。 所以让html像这样:
<div id="1">I_want_to_make_div_width_equal_to_this_word</div>
<div id="2">I_want_to_make_div_width_equal_to_this_word
<br/>and_anther_word_in_next_line
</div>
<div id="3">
<span>I_want_to_make_div_width_equal_to_this_word</span>
<span>and_anther_word_in_next_line</span>
</div>
这样的CSS:
div span{
display:block;
}