Lovelock
Lovelock

Reputation: 8085

Making all lines in a paragraph the same width regardless character count

I am making a GUI for a clients website. Its a T Shirt website where they want a really simple designer with limited options.

This is fine, however one of the options they have requested is to easily make all lines the same width. This results in larger font for some lines.

The provided text is in one text field, I then use:

word-wrap: break-word;

to break that line to fill the container.

This would end up as the example on the right, instead of the left.

enter image description here

Would this be possible with CSS prefered but JS can be used too.

Upvotes: 1

Views: 3132

Answers (3)

Hugo Silva
Hugo Silva

Reputation: 6948

You can increase the font size until the text gets wider than the parent. Have a look at this recursive function (using jQuery):

function findLargestFontSize($line){
    var oldSize = parseInt($line.css('font-size'));
    //set new size
    $line.css('font-size', oldSize + 1 + 'px');
    // check if hit the edges
    if( $line.width() > $line.parent().width() ){
        $line.css('font-size', oldSize + 'px');
        return(oldSize);
    } else {
        findLargestFontSize($line);
    }
}

And a fiddle with an example.


EDIT

I found Amit's answer to be a lot more elegant than this, so I merged with my solution. Here is another fiddle

var $target = $('#target');
var words = $target.text().split(' ');

// split words into lines
$target.empty();  
for(var i = 0; i < words.length; i++){
    var $newLine = $('<span style="display: table;">' + words[i] + '</span>');
    $target.append($newLine);
    if($newLine.width() < $target.width()) {
        $newLine.css('font-size', parseInt( $newLine.css('font-size'))  * ( $target.width() / $newLine.width()) + 'px');
    }
};       

Upvotes: 1

Amit
Amit

Reputation: 46323

If you don't mind breaking each line into it's own container (span or any other...) you can do it with javascript. The key is font-size CSS attribute.

You need to calculate the widest line (use offsetWidth to get each line's width), then calculate for each line how much spare width it leaves, divide that by the length of text in the line multiply by your base font size and set the attribute.

Here's a working fiddle.

Upvotes: 1

David Mulder
David Mulder

Reputation: 26995

The BigText jQuery plugin is capable of doing exactly what you wish to do.

$('#bigtext').bigtext();
#bigtext{
  width:300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://zachleat.github.io/BigText/dist/bigtext.js"></script>
<div id="bigtext">
  <span>SOME</span>
  <span>TOTALLY</span>
  <span>HIPSTER</span>
  <span>QUOTE</span>
  <span>ABOUT</span>
  <span>LIFE</span>
</div>

Upvotes: 1

Related Questions