csswidthformulaviewportfont-size

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


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

objective


Solution

  • 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.