Reputation:
I’ve been struggling with text resizing. I am using Dark Sky’s awesome weather api to return summary text to my display. As the text content can change with the weather, sometimes there are are one or two words, sometimes a few more.
I have a fixed size div on my page, and would like to the api response to always be as big as possible, but wrap across the line space within the div. I’ve seen many examples and plug-ins that do similar but force the text on to one line only.
Code below in snippet
$(document).ready(function() {
resize_to_fit();
});
function resize_to_fit() {
var fontsize = $('div#outer div').css('font-size');
$('div#outer div').css('font-size', parseFloat(fontsize) - 1);
if ($('div#outer div').height() >= $('div#outer').height()) {
resize_to_fit();
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer" style="width:200px; height:200px; border:1px solid red;">
<div>bad weather</div>
</div>
Above is a good example, from SO, but does not increase the font size to fill the div when there are only one or two words. Can anyone point me in the direction of enhancing the above code to achieve this? Thanks
Upvotes: 0
Views: 3753
Reputation: 619
You can try this with font-size:260%
$(document).ready(function() {
resize_to_fit();
});
function resize_to_fit() {
var fontsize = $('div#outer div').css('font-size');
$('div#outer div').css('font-size', parseFloat(fontsize) - 1);
if ($('div#outer div').height() >= $('div#outer').height()) {
resize_to_fit();
}
}
#outer{
font-size:260%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="outer" style="width:200px; height:200px; border:1px solid red;">
<div>bad weather</div>
</div>
Upvotes: 1
Reputation: 216
There is a CSS3 method to achieve what you're specifying. You can use viewport units to get the text from your API call to resize with accordance to your fixed div. Lets say you gave your text an id, #resize. The the code would look like this:
#resize {
font-size: 30px; //fallback
font-soze: 3.5vw; //adjust till satisfactory.
}
This way, you wouldn't have to worry about using javascript to resize the text.(Save load time!)
Pure CSS to make font-size responsive based on dynamic amount of characters
https://css-tricks.com/viewport-sized-typography/
https://medium.com/@mrsallee/pixel-free-css-66bddb327bb1
Upvotes: -1