Newspapers often style the heading font for each story according to how much space the words take up. For instance, in this spread, you can see text has been styled to fit one line:
http://www.newsdesigner.com/blog/images/feb05/best/hc6.php
And on this one, you can see different sizes for each headline according to the article size.
http://www.snd.org/snd28/worldsbest/Aripaev_files/Aripaev08.jpg
Is it possible, using some combination of CSS and jquery, to apply styling rules to a heading according to it's length? So for a short heading "A Short Heading" would have a larger 开发者_如何学Gofont-size and letter-spacing to fit within one line. And "Slightly Longer Heading for an Article Title" would have a smaller font-size and letter-spacing to fit into two lines.
To keep this simple, assume the heading sits above a one-column fixed-width (400px) text block.
I had asked a question like this some time back, but don't recall getting a very good response. Today, though, I have a couple of ideas.
Heading Height vs Single Character Height
For each heading, you could check the height of the heading vs the height of the heading if it had only the first letter (creating a copy of the heading, truncate its text, and check its height off-screen). For instance:
"This is a very long heading" may be 125px tall, where as "T" may only be 42px tall. You could then setup a loop that shrinks the font-size by 1 pixel until the height of the heading is equal to or less than 42px.
Replace Spaces, and Shrink
Another method would be to replace all of the spaces with non-breaking spaces, and then shrink until the width of the header is equal to or less than that of its parent.
As a starting point, suppose you have a class "long" that provides alternative styling for titles longer than the value of the variable "threshold". Then you can set this class on long headings using
$(':header').each(function () {
$(this).toggleClass('long',$(this).text().length > threshold);
})
This is certainly possible to do, but difficult to do well. A basic alogrithm to do this is to first determine how big your string can be. Next, create your string in a specific size and then see if it is "close enough" to your target. If not, recreate the string in a new size/style and repeat.
Here's a link that will show you how to measure the size of a string in JavaScript: http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/
精彩评论