Avoiding line wrapping unless necessary with CSS

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.


    Simply make s2 (or, optionally, both s1 and s2) an inline block:

    #s2 {
        display: inline-block;
    }
    

    This allows the entire s2 box to flow on the same line as s1 when there's sufficient space, before wrapping as described in your second point, and then its contents as described in your third point (because the inline block then behaves like your container block element when resizing and wrapping its contents). This is detailed in the spec in case you're interested.

    Updated fiddle


    The other way:

    display: block;
    float: left;
    

    And also dont't forget to give a clearfix to the parent element;

    DEMO

    链接地址: http://www.djcxy.com/p/88338.html

    上一篇: 静态/固定侧栏和流体内容

    下一篇: 除非需要使用CSS,否则避免换行