6

I want to display a short text-align-centered sentence like this.

<p style="font-size: 13px; text-align: center; width: 600px;">
This is a variable-length sentence which is sometimes only a few words and sometimes up to three lines long.
</p>

This is a variable-length sentence which is sometimes only a few words and sometimes up to three lines long.

What happens now is that, because of the width, the last two words "lines long" fall on the next line of the paragraph. In a centered alignment this looks rather ugly. My current method of solving this is to manually insert a break in the right place.

<p style="font-size: 13px; text-align: center; width: 600px;">
This is a variable-length sentence which is sometimes<br/>only a few words and sometimes up to three lines long.
</p>

This is a variable-length sentence which is sometimes
only a few words and sometimes up to three lines long.

This becomes tiring to do all the time. Is there a way in HTML do this automatically? So basically to first let a "p" element determine the minimum number of lines it needs to show the text, and then to shrink it horizontally as much as possible, while keeping the same number of lines?

Hildo Bijl
  • 83
  • 1
  • 4
  • 2
    `text-align: justify` – Michelangelo Jul 05 '15 at 21:56
  • Please don't use inline style attributes :-) – Toni Leigh Jul 05 '15 at 22:05
  • @Toni: I usually don't, but I wasn't about to include a whole CSS style file on StackExchange, am I? – Hildo Bijl Jul 06 '15 at 07:56
  • @Mikey: Even with justified alignment, you still get those straggling few last words on the last line, which is what I'm looking to avoid. Guess I might have to use Javascript to fix it, which I'd rather not. – Hildo Bijl Jul 06 '15 at 07:56
  • @HildoBijl You might want to take a look at this jQuery plugin https://github.com/jquery-textfill/jquery-textfill – Michelangelo Jul 06 '15 at 09:43
  • @HildoBijl, fair enough - it's just something I've seen a lot that so I like to point out that's it's not good in production code – Toni Leigh Jul 06 '15 at 10:58
  • @Mikey: That looks interesting. Though not exactly what I wanted - I want to adjust the width of the container and not the font size of the contents - I can simply steal the idea and write my own code for it. It'll be Javascript instead of just CSS, but it'll have to do. Thanks for the idea! – Hildo Bijl Jul 06 '15 at 13:17

1 Answers1

1

The closest you can get with CSS is text-align: justify;

p {
  font-size: 13px;
  text-align: justify;
}

p#first {
  width: 100px;
}

p#second {
  width: 150px;
}
<p id="first">
This is a variable-length sentence which is sometimes only a few words and sometimes up to three lines long.
</p>

<p id="second">
This is a variable-length sentence which is sometimes only a few words and sometimes up to three lines long.
</p>
TechWisdom
  • 3,960
  • 4
  • 33
  • 40