Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Avoiding line wrapping unless necessary with CSS

Tags:

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.

like image 545
Vaughan Avatar asked Jun 29 '26 16:06

Vaughan


2 Answers

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

like image 148
BoltClock Avatar answered Jul 02 '26 18:07

BoltClock


The other way:

display: block;
float: left;

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

DEMO

like image 45
Mihey Egoroff Avatar answered Jul 02 '26 18:07

Mihey Egoroff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!