Reputation: 8085
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.
Would this be possible with CSS prefered but JS can be used too.
Upvotes: 1
Views: 3132
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);
}
}
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
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
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