How to Autoscale the Font Size to Fit the Contents of a Div

How can I autoscale the font size to fit the contents of a div?

Contrary-wise. You could wrap the text in an interior DIV, measure its width with JavaScript. Test if that width is wider than the parent DIV. Get the current font size, and incrementally move it down 1px at a time until inner DIV's width is less than or equal to the outer DIV's width.

Font scaling based on width of container

If the container is not the body, CSS Tricks covers all of your options in Fitting Text to a Container.

If the container is the body, what you are looking for is Viewport-percentage lengths:

The viewport-percentage lengths are relative to the size of the initial containing block. When the height or width of the initial containing block is changed, they are scaled accordingly. However, when the value of overflow on the root element is auto, any scroll bars are assumed not to exist.

The values are:

  • vw (% of the viewport width)
  • vh (% of the viewport height)
  • vi (1% of the viewport size in the direction of the root element's inline axis)
  • vb (1% of the viewport size in the direction of the root element's block axis)
  • vmin (the smaller of vw or vh)
  • vmax (the larger or vw or vh)

1 v* is equal to 1% of the initial containing block.

Using it looks like this:

p {
font-size: 4vw;
}

As you can see, when the viewport width increases, so do the font-size, without needing to use media queries.

These values are a sizing unit, just like px or em, so they can be used to size other elements as well, such as width, margin, or padding.

Browser support is pretty good, but you'll likely need a fallback, such as:

p {
font-size: 16px;
font-size: 4vw;
}

Check out the support statistics: http://caniuse.com/#feat=viewport-units.

Also, check out CSS-Tricks for a broader look: Viewport Sized Typography

Here's a nice article about setting minimum/maximum sizes and exercising a bit more control over the sizes: Precise control over responsive typography

And here's an article about setting your size using calc() so that the text fills the viewport: http://codepen.io/CrocoDillon/pen/fBJxu

Also, please view this article, which uses a technique dubbed 'molten leading' to adjust the line-height as well. Molten Leading in CSS

Auto scale font size in CSS

Per your comment you are open to use Javascript, hence proposing a Javascript solution (actually using jQuery). Hope you understand that this is not possible with only CSS.

All you need is to define your threshold for height. For example, if you decide that you need to accommodate your text in a p with a maximum height of 100px, then you loop and keep reducing the font-size until the threshold height is reached.

Something like this:

var threshold = 100, /* define height to restrict */
p = $('#p'), /* your element depending on whatever selector */
fs = parseInt(p.css('font-size')); /* get the current font size */

while (p.height() > threshold) { /* while height is more than threshold */
p.css({'font-size': fs-- }); /* reduce the font-size */
}
p.height(threshold); /* adjust the final height to clean up */

You might need to adjust the final height a little bit after the loop.

Demo fiddle: http://jsfiddle.net/abhitalks/ab6m7yh1/2/

Demo Snippet:

var threshold = 100;
$('p').each(function() { var $self = $(this), fs = parseInt($self.css('font-size')); while($self.height() > threshold) { $self.css({'font-size': fs-- }); } $self.height(threshold);});
p { font-size: 2em; width: 320px; height: auto; border: 1px solid #ccc; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. </p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </p><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. </p>

Resize font-size according to div size

In regards to your code, see @Coulton. You'll need to use JavaScript.

Checkout either FitText (it does work in IE, they just ballsed their site somehow) or BigText.

FitText will allow you to scale some text in relation to the container it is in, while BigText is more about resizing different sections of text to be the same width within the container.

BigText will set your string to exactly the width of the container, whereas FitText is less pixel perfect. It starts by setting the font-size at 1/10th of the container element's width. It doesn't work very well with all fonts by default, but it has a setting which allows you to decrease or increase the 'power' of the re-size. It also allows you to set a min and max font-size. It will take a bit of fiddling to get working the first time, but does work great.

http://marabeas.io <- playing with it currently here. As far as I understand, BigText wouldn't work in my context at all.

For those of you using Angularjs, here's an Angular version of FitText I've made.


Here's a LESS mixin you can use to make @humanityANDpeace's solution a little more pretty:

@mqIterations: 19;
.fontResize(@i) when (@i > 0) {
@media all and (min-width: 100px * @i) { body { font-size:0.2em * @i; } }
.fontResize((@i - 1));
}
.fontResize(@mqIterations);

And an SCSS version thanks to @NIXin!

$mqIterations: 19;
@mixin fontResize($iterations) {
$i: 1;
@while $i <= $iterations {
@media all and (min-width: 100px * $i) { body { font-size:0.2em * $i; } }
$i: $i + 1;
}
}
@include fontResize($mqIterations);

Have text scale up in size to fit the container

One thing that I have done that isnt perfect but can get the job done in some cases is to use a @media rule for screen sizes smaller then X pixels, set the font size smaller or larger.

h2{
font-size:25px
}

@media screen and (max-width: 850px){/* for screens smaller then 850px, set the font size smaller */
h2{
font-size:19px;
}
}

Of course this would only work assuming the texts container size is based on the window size in some way.

GWT Auto Scale Text font size to Fit within Bounds

There are sevaral solutions to this problem:

(1) render the text, measure its width (myLabel.getOffsetWidth(), compare to the desired width, change font size if it does not fit and start over (remember to do this inside the Scheduler's deferred command, or your offset width will be zero);

(2) use FitText.js (http://fittextjs.com/);

(3) use canvas which can auto-fit text into provided space;

(4) use ellipsis when text overflows;

(5) use viewport units for text font (limited browser support at this time): http://css-tricks.com/viewport-sized-typography/

(6) create a different, more fluid UI design that handles content size better.

How to automatically change the text size inside a div?

I understand your question this way, you would like to fit some text into a given div with a fixed dimension, and if the div is too small to show all the text, the font size should be shrinked until the text fits into the div. If that's the point, here is my solution.

Here is an example with a jQuery implementaion: http://jsfiddle.net/MYSVL/2/

Here is a div

<div id="fitin">
<div>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.</div>
</div>

With a fixed size

#fitin {
width: 300px;
height: 100px;
border: 1px solid black;
overflow: hidden;
font-size: 1em;
}

This JavaScript will do the job.

$(function() {
while( $('#fitin div').height() > $('#fitin').height() ) {
$('#fitin div').css('font-size', (parseInt($('#fitin div').css('font-size')) - 1) + "px" );
}
});


Related Topics



Leave a reply



Submit