Reputation: 438
;Is it possible?
I have many single lined paragraphs and they all need to be at most 1 line (due to various functions I have on each paragraph). I can set them all to a width with css, or (what I have at the moment):
var max = 0;
$(this).find('p').each(function(){
if ($(this).width() > max)
max = $(this).width();
});
$(this).find('p').width(max);
});
text-align: justify; <<< does nothing to one line
But is there a way to justify one line? Without or with letter spacing calculations? Or working css3 solutions?
Upvotes: 1
Views: 1923
Reputation: 41
Here's an answer that works. Like I mentioned above, you can determine the height of a 1-line paragraph and run this jquery on any paragraphs smaller. InnerWrap your paragraph with SPAN, this will allow you to get the width of the line of text.
Next find the difference between the P width and SPAN width, this will give you the spacing from the end of the line to the edge. You can then divide this by the number of spaces in the text, giving you the word-spacing you'll need to justify your line.
HTML, innerWrap all your P tags with span: (or you can do this with jquery too)
<p><span>This is my one line paragraph</span></p>
jQuery, do some math:
$('p').each(function() {
var pHeight = $(this).height();
var pWidth = $(this).width();
if (pHeight <= 20) {
// Get the width of the span:
var spanWidth = $(this).find('span').width();
// Get the width difference between the P and Span
var widthDiff = pWidth - spanWidth;
// Count # of spaces:
var spaces = $(this).html().split(' ').length - 1;
// Divide to find word spacing:
var spacing = widthDiff / spaces;
$(this).css('word-spacing',spacing);
}
});
Check it out on JSFiddle : http://jsfiddle.net/wjmZP/3/
Upvotes: 1
Reputation: 49208
I knew there would be an answer using :after
.
p {
text-align: justify;
}
p:after {
content: "";
display: inline-block;
width: 100%;
}
Simple and effective. Props to Vjeux for the solution.
Upvotes: 3
Reputation: 41
Try to determine the max height of a one-line paragraph, let's say it's 24px.
$('p').each(function() {
var pHeight = $(this).height();
if (pHeight <= 24) {
$(this).addClass('justify');
}
});
// css
p.justify { text-align: justify; }
Once you find that magic height number, you should be fine.
Upvotes: 0