Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular.js: How to reduce font size dynamically based on characters' length?

I am using following code to display name dynamically:

<div id="name">{{profile.name}}</div>

Screen size is always 320px It works fine if name is short but if name is very long then name is broken in two lines that disturbs my layout. So I want to reduce font size automatically if name becomes too long...

So is there any way to watch content of div and apply different font size dynamically based on character length ?

like image 679
zzzzz Avatar asked May 20 '16 09:05

zzzzz


People also ask

How do I automatically adjust font size in CSS?

The font-size-adjust property of CSS tells the browser to adjust the font size of the text to the same size regardless of font family. When the first chosen font is not available, the font-size-adjust property allows you more control over the font size.

What attributes change font size?

In HTML, you can change the size of text with the <font> tag using the size attribute.

Which property allows you to control the size of the font?

The font-size-adjust property gives you better control of the font size when the first selected font is not available.

Which property of CSS helps to control the size of the font?

The font-size CSS property sets the size of the font.


2 Answers

Use ng-class to attach a class to the element when the name is long

<div id="name" ng-class="{'long': (profile.name.length > 20), 'verylong': (profile.name.length > 40)}">{{profile.name}}</div>

And then use the class to change font-size in your CSS.

like image 103
C14L Avatar answered Oct 18 '22 06:10

C14L


<!DOCTYPE html>
<html>
<head>
    <title>change font size according to text length</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>
<!--change text inside below division if the string length is 20 or more it's font size will be 14px else 50px-->
<div id="text">Hello There I'm testing this text font size...!!!</div>

<script type="text/javascript">
    jQuery( document ).ready(function() {
        var length = jQuery('#text').html().length;
        //change length at which you want to change font-size
        if(length >= 20){
            //enter font-size if text is long
            $("#text").css({'font-size':'14px'});
        } else {
            //enter font-size if text is short
            $("#text").css({'font-size':'50px'});
        }
    });
</script>
</body>
</html>

You can change values according to your needs...! :) This Solution is for JQuery.

like image 1
Kalrav Joshi Avatar answered Oct 18 '22 07:10

Kalrav Joshi