CSS text justify with letter spacing

2019-01-14 11:27发布

Is there a way to automatically justify words using letter spacing, each in its row, to a defined width, using CSS?

For example, "Something like this" would look, well, something like this:

"Something like this" would look something like this

Is there a non-obtrusive way to apply such styling to my text? I believe pure CSS doesn't have this option (at least not with CSS versions before 3, CSS3 seems to have a text-justify property, but it's not well supported yet), so js solutions would be fine also.

9条回答
Animai°情兽
2楼-- · 2019-01-14 12:03

What is wrong with text-align: justify? I think I might be misunderstanding your question.

查看更多
beautiful°
3楼-- · 2019-01-14 12:04

I know this is an old topic, but I faced this the other night. And found a suitable solution using tables.

Every letter shall be put into a <td> </td> I know it looks tedious, but if you wanna do this, it would be for a word or two, right? Or you always can use JS to fill it if is too much. However, this is only CSS and very versatile solution.

Using letter-spacing the letters get distributed properly. You should play around with it, depending on the width of the table.

#justify {
  width: 300px;
  letter-spacing: 0.5em;
}
<table id="justify">
  <tbody>
    <tr>
      <td>J</td>
      <td>U</td>
      <td>S</td>
      <td>T</td>
      <td>I</td>
      <td>F</td>
      <td>Y</td>
    </tr>
  </tbody>
</table>

See the example here

Crossbrowser safe, virtually nothing shall differ. Is just CSS.

I used it in My website which is in english and spanish. the subtitle under my name in spanish has an additional letter and it will step out the width. Using the tables explained above, it gets distributed to the same width automatically. Spacing it manually I'd had to define a whole condition for each language to go around that.

查看更多
疯言疯语
4楼-- · 2019-01-14 12:04

The css only solution is text-justify: distribute https://www.w3.org/TR/css-text-3/#text-justify but the support is still very poor.

A small experiment using text-align-last: justify and adding spaces between letters.

div{
	display:inline-block;
	text-align: justify;
	text-align-last: justify;
	letter-spacing: -0.1em;
}
<div>
S o m e t h i n g<br>
l i k e<br>
t h i s
</div>

查看更多
登录 后发表回答