Dynamic font sizing in CSS allows text on a webpage to

I am working on creating a dynamic screen using AngularJS.

Within this screen, there are objects with a specific size:

.item
{
  margin: auto;
  margin-bottom: 10px;
  width: 11vw;
  height: 11vw;
  text-overflow: ellipsis;
  overflow: hidden;
}

These items are inserted through an ng-repeat loop based on the data returned from an API.

<div class="item"
       ng-click="ctrl.clickFunction()"
       ng-style="{'background-color':ctrl.color }">
    <div class="itemGlobalCode">{{::ctrl.name}}</div>
  </div>

The issue I am facing is that the items are round and for better visualization, I want to adjust the font size of the content (in this case ctrl.name) if it exceeds the container size.

I have explored some jQuery solutions but ideally, I would prefer to find a pure CSS solution. Do you have any suggestions?

Answer №1

If you need to adjust the font size dynamically in Angular, there are a few ways to do it. One option is to use ng-style with a ternary expression:

Ternary

<div class="itemGlobalCode"
     ng-style="{'font-size': ctrl.name.length > 10 ? '12px' : '14px'}"></div>

Another approach is to create a method in your controller to handle the font size logic:

Method

Controller

$scope.getFontSize(ctrlName) {
    if (ctrlName.length > 10) {
        return '12px';
    }

    return '14px';
};

Then, in your view, you can call this method within ng-style:

<div class="itemGlobalCode"
     ng-style="{'font-size': getFontSize(ctrl.name)}"></div>

Lastly, you can utilize ng-class to apply different font sizes based on conditions:

Plus: ng-class

You can also define CSS classes for different font sizes:

CSS

.itemSmall {
    font-size: 12px;
}
.itemBig {
    font-size: 14px
}

Then, in your view, you can use ng-class to apply these classes dynamically:

<div class="itemGlobalCode"
     ng-class="{'itemSmall': ctrl.name.length > 10, 'itemBig': ctrl.name.length <= 10}"></div>

Answer №2

To implement dynamic CSS classes, you can utilize the ng-class directive

<div class="item"
   ng-click="ctrl.clickFunction()"
   ng-class="{'css-class1':condition1, 'css-class2':condition2() }">
<div class="itemGlobalCode">{{::ctrl.name}}</div>

In your controller:

$scope.condition1 = true;
$scope.condition2 = function(input) {
     // Perform calculations or logic with input
    return input.isTrue();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it necessary for me to replicate this function? - jQuery

I have developed a function that creates a transparent information overlay on a current div for a mobile web app. Context: I am using jQTouch, which means I have separate divs instead of loading individual pages anew. $(document).ready(function() { ...

What is the best way to output multiple Div elements using Jquery or Javascript?

I have the following HTML code snippet: <div id="box"> <div id="id_1></div> <div id="id_2></div> <div id="id_3></div> <div id="id_4></div> </div> Can someone guide me on how to use Jquery or ...

I am having difficulty retrieving all the cssRules for certain pages

Attempting to retrieve all CSS rules using JavaScript has yielded varying results. For instance, on StackOverflow, the code used is: console.log( document.styleSheets[1].href,'rules', document.styleSheets[1].cssRules,'Should be css rules, ...

Determine the placement of the body with CSS styling

Here is the code snippet from my website: body { background-image: url('background.jpg'); background-repeat: no-repeat; background-attachment: fixed; background-size: cover; } .centered { /* Center entire body */ display: flex; ...

Fetch data dynamically with jQuery AJAX

I am working on a jQuery Ajax form submission to a PHP page with the goal of dynamically returning values instead of all at once. For instance, in my jQuery code: jQuery.ajax({ type: "POST", url: "$PathToActions/Accounts.php", dataType: ...

Enhancing React Functionality: Increasing React State Following an If Statement

Whenever I click on the start/stop button, it triggers the handlePlay function. This function then proceeds to initiate the playBeat function. In an ideal scenario, the play beat function should continuously display 1222122212221222... until I press the st ...

Tips for abbreviating HTML content using PHP

Similar Question: PHP: Truncate HTML, ignoring tags I have some HTML content stored in a database. I need to display this content in a shortened form. I attempted to use the mb_strstr function like so; $str = mb_strstr($this->htmlData, "</p> ...

Upon refreshing the page, nested React routes may fail to display

When I navigate to the main routes and their nested routes, everything works fine. However, I encounter an issue specifically with the nested routes like /register. When I try to refresh the page, it comes up blank with no errors in the console. The main r ...

What is the optimal method for creating and testing AJAX applications on a local server, then effortlessly deploying them online?

Exploring AJAX development is new to me. The challenge I've encountered so far is dealing with the same-origin policy, which requires modifying host information strings like absolute URLs in JavaScript files every time I deploy local files to remote s ...

Passing a reference to a react functional component (react.FC) results in a type error: The property ref is not recognized on the type 'IntrinsicAttributes & Props & { children: ReactNode}'

Currently, I am working on mastering the utilization of forward refs. In a functional component (FC), I am trying to initialize all my refs and then pass them down to its child components so that I can access the canvas instances of some chartjs charts. Ho ...

The fitBounds and panToBounds functions in react-google-maps fail to properly adjust the map's size

const Map = withGoogleMap(props => { const { activeMarker, zoom, center, showInfoWindow, products } = props; const [selectedPlace, setSelectedPlace] = useState(null); // Code to iterate through items and adjust map size, center, and zoom to inclu ...

Why isn't my output being shown on the screen?

Why is the output (refresh value) not being displayed? function myFunction() { $a = document.getElementById("examplehtml").value; document.write("<big><bold>"); document.write($a); document.write("</bold></big>"); $b = ...

Display or conceal form elements depending on the JSON response

Upon making an api call, a json Response is received with the following structure: {"Field":"Amount","FieldName":"Amount","FieldType":"Numeric","MaximumLength":128,"MinimumLength":0,"Options":"Mandatory"} This api call yields between 5-10 of these object ...

The image I want to show is invisible on the CSS custom radio button

I'm having trouble creating a custom radio button that displays the image I want. The current setup doesn't seem to be working as expected. label { font-weight: lighter; cursor:pointer; } input[type="radio"] { display:none; } in ...

In order to enable automatic playback of background images

Having created a slider with hover functionality on icons to change background images, I now seek to add an autoplay feature to the slider. The slider was implemented in a WordPress project using Elementor and involved custom Slider creation through JavaSc ...

The battle between ui-sref-active and $state.includes() is a topic of

I am attempting to highlight the clicked area by adding an active class using ui-sref-active. Unfortunately, it is not working with $state.includes(), even though I can see its value as true in the controller. Can someone assist me with this issue? See th ...

Calculating the number of duplicate lines in a file with node.js

I am currently working on a project where I need to read a large .csv file line by line, extract the first column (which contains country names), and then count the number of duplicates for each country. For example, if the file contains: USA UK USA The ...

Personalize Tooltip on Highchart Area Chart

I am currently in the process of customizing the tooltip for my area chart using Highchart. Within this area chart, I have plotted 3 series. My goal is to display the tooltip at a fixed location on the chart's top center. When hovering over any point ...

Error: The property 'length' cannot be read from an undefined parent causing Uncaught TypeError

Hey there, take a look at this cool stuff http://jsfiddle.net/J9Tza/ <form class="validation"> <div> <input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" pattern=".{3,200}" title="3 to 200 characters" r ...

Enabling Multiple Login Feature in Node.js

const handleLogin = async (req, res) => { const User = require("../models/user"); const LoginInfo = require('../models/login_info'); try { const { email, mobile, password, otp } = req.body; const params = []; if(ema ...