2

Is it possible to use CSS to automatically control line wrapping in such a way that the following happens as the browser window is resized:

  • s1 and s2 stay on the same line when they can both fit within the div
  • s2 drops to a second line when they can no longer both fit without wrapping
  • s2 wraps when it can no longer fit within the div

HTML:

<body>
    <div>
        <span id="s1">Lorem ipsum dolor:</span>
        <span id="s2">sit amet consectetur adipiscing eli</span>
    </div>
</body>

So three possible views are:

1:

Lorem ipsum dolor: sit amet consectetur adipiscing eli

2:

Lorem ipsum dolor:
sit amet consectetur adipiscing eli

3:

Lorem ipsum dolor:
sit amet consectetur
adipiscing eli

The words in s1 are always the same, but the words in s2 can vary so I can't just alter white-space:nowrap based on the width of the page.

Browser support is not a big issue, once it works in Chrome and/or Firefox.

Here's a simple JSFiddle you can work with.

4

2 回答 2

6

只需将 s2(或者,可选地,s1 和 s2)都设为内联块:

#s2 {
    display: inline-block;
}

当有足够的空间时,这允许整个 s2 框在与 s1 相同的行上流动,然后按照您的第二点中所述进行包装,然后按照您的第三点中所述的内容(因为内联块的行为就像您的容器块元素调整大小和包装其内容时)。如果您感兴趣,请参阅规范中的详细信息。

更新的小提琴

于 2013-10-26T14:45:33.783 回答
1

另一种方法:

display: block;
float: left;

并且不要忘记给父元素一个clearfix;

演示

于 2013-10-26T14:55:07.000 回答