CSS: How can I adjust my font size fill all the space in a justified layout?

一曲冷凌霜 提交于 2019-12-18 09:46:12

问题


How can I make my text look like the image below using CSS?


回答1:


First of all you need to use a mono-space font. You can find some pretty nice looking ones over at Google Fonts. The font in the image is Ubuntu Mono.

Secondly, we are going to be using Viewport Width, or 'vw' unit (If you clicked the link, you'd see that it is well supported by browsers). You need to make sure the top line of text is the width you need it be to fit the width. This also means that each line needs to be it's own element. Some example HTML:

<p style="font-size: 5vw;">How can I</p>
<p>Adjust my font size</p>
<p>to fill all the space</p>
<p>in a justified</p>
<p>layout?</p>

We can now use this initial place-holder to work out the 'vw' size for the rest of the lines using the following formula:

NewFontSize = BaseFontSize - (((NewLineNumberOfChars - BaseLineNumberOfChars) / NewLineNumberOfChars) * BaseFontSize)

I have created this example to show how this can be achieved programmatically with JavaScript (I used JQuery for ease). The code that it spits out is as follows:

<p style="font-size: 5vw;">How can I</p>
<p style="font-size: 2.36842vw;">Adjust my font size</p>
<p style="font-size: 2.14286vw;">to fill all the space</p>
<p style="font-size: 3.21429vw;">in a justified</p>
<p style="font-size: 6.42857vw;">layout?</p>

It should be noted that because Google Chrome rounds all font sizes to the nearest round pixel (boo-hiss), it's not exact and it can look off, especially at smaller sizes.



来源:https://stackoverflow.com/questions/25289198/css-how-can-i-adjust-my-font-size-fill-all-the-space-in-a-justified-layout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!