0

I have a simple HTML list:

<ul>
  <li>First Item</li>
  <li>Second Item</li>
  <li>Third Item</li>
</ul>

I want to display the list with the following features:

  1. Items in a row.
  2. List would have a maximum width, after which items are expected to break to the next line.
  3. Items should only break on beginning / spaces (not mid-word).
  4. Lines should contain the most text possible before breaking.

Desired outcome:

[   maximum width   ]
First Item * Second
Item * Third Item

Failed attempts:

#1 (word breaks)

[   maximum width   ]
First Item * Second I
tem * Third Item

#2 (item doesn't break properly)

[   maximum width   ]
First Item * Second Item
* Third Item

#3 (line breaks "prematurely")

[   maximum width   ]
First
Item * Second Item *
Third Item

Update: A simple li {display: inline;} won't work if the HTML is not indented / spaced (some frameworks -- say, GatsbyJS -- automatically "squeeze" the HTML):

<ul><li>First Item</li><li>Second Item</li><li>Third Item</li></ul>

(Fiddle example)

Eyal Roth
  • 3,895
  • 6
  • 34
  • 45

2 Answers2

1

As Temani already said li {display: inline;} works fine. (Fiddle)

Lueton
  • 171
  • 1
  • 12
  • This seems to work fine with plain HTML, but doesn't work for me with GatsbyJS (getting #3). I've noticed that with the gatsby version, the first item (which has 2 white-spaces and breaks prematurely) has one less glyph in the rendered fonts view (Dev tools -> Elements -> Styles -> Computed -> Rendered fonts). What could this mean? Perhaps something with my environment? My gatsby server is running via WSL. – Eyal Roth Jul 14 '19 at 15:00
  • OK that's not GatsbyJS per se. This won't work when the HTML is not indented: https://jsfiddle.net/8puLkcry/ – Eyal Roth Jul 14 '19 at 15:12
0

This seems to work for me:

ul {
    max-width: 100px;
}
ul li {
    display: inline;
}
ul li::after {
  content:" ";
}

Why the after part?

Well, unless there is a white-space / new-line after each <li> in the HTML source, the line won't break at the end of items, which may very well cause a "premature" line-break (as in the failed attempt #3). Some frameworks automatically "squeeze" the HTML -- basically removing these white-spaces -- and this requires an explicit space to be added after each item.

Here's a Fiddle examples (try removing the after from the css and see how you get failed attempt #3).

Eyal Roth
  • 3,895
  • 6
  • 34
  • 45