0

I need to shrink text when user resizes items, so that it fits in the container. Currently in my application I'm changing font-size dynamically, but that's not really optimal way. Is there a more effective way to change font-size according to its parent element's size using js or css?

Here is a simple fiddle: https://jsfiddle.net/vaxobasilidze/n5tqm563/5/

Vaxo Basilidze
  • 1,017
  • 13
  • 31
  • Based on https://stackoverflow.com/questions/16056591/font-scaling-based-on-width-of-container it looks like if you are doing user resizing without tying the width to the viewport width, js may be your only way. – JasonB Feb 24 '18 at 06:50
  • @JasonB How do I do this? I don't mean changing font-size using js, I'm already doing that in my app. – Vaxo Basilidze Feb 24 '18 at 06:55

1 Answers1

0

If you want the font-size to change based on the screen size, you can use viewport sizes, like so:

div {
    border: 2px solid;
    padding: 20px; 
    width: 300px;
    resize: both;
    overflow: auto;
    font-size: 5vmin;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/0.4.0/ResizeSensor.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/css-element-queries/0.4.0/ElementQueries.min.js"></script>
<div>
Some long text goes there...
</div>

However, if you want the font-size to change based on the user resizing the parent container, Javascript is the only way. You don't have to reinvent the wheel either as there are a lot of plugins already available to do the work for you.
You can refer here for more details: resize font-size according to div size

Rocks
  • 1,145
  • 9
  • 13