Dan Kaufman Dan Kaufman - 17 days ago 7
CSS Question

How would you vertically justify text with css/Javascript?

We have a

div
on our site and want to vertically JUSTIFY the text within it (not vertical align or center- justify).

Here's a basic example (using Bootstrap 3+, btw):

<div class="row">
<div class="col-xs-12 col-sm-4 v-justify">
this is our text that we need verticlaly justified. lorem ipsum dolor amet, etc...
</div>
<div class="col-xs-12 col-sm-4 portCell">
This is a div with a responsive image in it so we don't know the height.
For arguments sake we'll say 300px
</div>
<div class="col-xs-12 col-sm-4 portCell">
This is a another div with a responsive image in it so we don't know the height.
For arguments sake we'll say 300px
</div>
</div>


How could we get the text in that first DIV to justify vertically. Bonus points for just CSS solution with media query-friendly styling for full device support.




Answer based on Andrew Rockwell's solution



This loops through by class (v-justify) so we could apply it to multiple areas on our site.


$('.v-justify').each(function(){
var justify = $(this);
var maxHeight = justify.parent().next('.portCell').height();
var fontSize = 1.5;
while ( maxHeight > justify.height() ) {
justify.css('font-size', (fontSize+=1.7) + 'px');
}
});

Answer

How's this: https://jsfiddle.net/sp3rLang/4/

var justify = document.getElementById('v-justify');
var maxHeight = justify.parentElement.clientHeight;
var fontSize = 1;
while ( maxHeight > justify.clientHeight ) {
    justify.style.fontSize = fontSize++ + 'px';
}
// the while loop will always break a font size over the maxHeight
justify.style.fontSize = ( fontSize - 1 ) + 'px';