Jack Pilowsky
Jack Pilowsky

Reputation: 2303

Forcing a string to break in HTML/CSS

I have a navigation bar made up of items in an unordered list:

<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
</ul>

But they would look better displayed as

Item<br>
1

With a forced break in between Item and 1

Edit: width is 190px.

I can't use HTML to add a <br> tag. Ideally, I was looking for a way to do it with CSS.

Upvotes: 0

Views: 95

Answers (4)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201768

You can set a small width on the li elements, effectively forcing line wrapping. If the content is really “Item 1” etc., or generally two words, you can set a very small width, forcing each word on a line of its own, e.g.:

li { width: 1em; }

However, I cannot see a reason why such rendering would be an improvement, and I suspect the real problem is somewhat different.

Upvotes: 0

pzin
pzin

Reputation: 4248

You could try to use word-spacing. Obviously 190 pixels corresponds to the parent width value. You can also give it a higher value so that the word coming after will never have enough place and force the line break to happen.

Something like this:

li {
  word-spacing: 190px;
}

Not sure if there is another way to achieve this without changing the markup.

Upvotes: 0

Peter Rasmussen
Peter Rasmussen

Reputation: 16942

You cannot do this with css only (if you can't change the mark up). You can only make the ul have a small width and force the number on the next line that way. But then the text would have to be equally long for all items.

You can do it with javacript however. Either by wrapping the text and number in tags with display block - or adding a <br> tag in between.

Upvotes: 1

Karl Laurentius Roos
Karl Laurentius Roos

Reputation: 4399

Let's say your markup looks like this then:

<ul>

    <li><span class="title">Item</span> <span class="number">1</span></li>
    <li><span class="title">Item</span> <span class="number">2</span></li>
    <li><span class="title">Item</span> <span class="number">2</span></li>

</ul>

Then what you have to do is get each <span> on its own row. It's simple.

.title, .number {
    display: block;
}

Since each <span> now is a block, they will take the full width of the container as default.

Upvotes: 1

Related Questions