Guide to aligning a fraction in the center of a percentage on a Materal Design progress bar

Greetings! My objective is to create a material progress bar with the fraction displayed at the top of the percentage.

Currently, I have managed to show the fraction at the beginning of the percentage. Below is the code snippet:

       <div class="card-body">
            <span id="advance-details" #advancedetails class="progress">{{ CurrentAmount }}
              <span >/ {{ OriginalAmount }}</span></span>
            <mat-progress-bar id="advance-meter" #advancemeter class="meter" color="primary" mode="determinate" [hidden]="!repaymentPercentage"  value="{{ repaymentPercentage }}"></mat-progress-bar>
            <div id="advance-progress" #advanceprogress class="meter-percentage"&‌e;> {{ repaymentPercentage }}% </div>
        </div>

and here is the corresponding typescript code:

setProgressBarElementsPosition() {

document.getElementById('advance-details')!.style.left = this.repaymentPercentage + "%";
document.getElementById('advance-progress')!.style.left = this.repaymentPercentage + "%";

let widthAdvanceDetails = document.getElementById('advance-details')?.getBoundingClientRect().width;
let positionAdvanceDetails = document.getElementById('advance-details')?.getBoundingClientRect().x;

let widthMeter = document.getElementById('advance-meter')?.getBoundingClientRect().width;
let positionMeter = document.getElementById('advance-meter')?.getBoundingClientRect().x;
let positionMeterEnd = positionMeter! + widthMeter!;

let widthPercentage = document.getElementById('advance-progress')?.getBoundingClientRect().width;
let positionPercentage = document.getElementById('advance-progress')?.getBoundingClientRect().x;

if (positionAdvanceDetails! + widthAdvanceDetails! > positionMeterEnd) {
  document.getElementById('advance-details')!.style.left = positionMeterEnd - positionMeter! - widthAdvanceDetails! + "px";
} else {
  document.getElementById('advance-details')!.style.left = this.repaymentPercentage + '%';
}
if (positionPercentage! + widthPercentage! > positionMeterEnd) {
  document.getElementById('advance-progress')!.style.left = positionMeterEnd - positionMeter! - widthPercentage! + "px";
} else {
  document.getElementById('advance-progress')!.style.left = this.repaymentPercentage + '%';
}
}

The current output resembles the image below:

I am aiming for the fraction value 11.00/11.00 to be positioned in the middle of the progress percentage. How can I achieve this?

Answer №1

Based on the comparison of your image and the sample image, it seems like you are aiming for the fraction to be positioned above the percentage number, centered, and moving along with the change in percentage.

To achieve this, I suggest utilizing a calculation like self.offsetWidth / 2 to determine the center of the element and incorporating that into your implementation as needed.

    <div style="width: 100%; display: flex; flex-direction: column">
      <div
        style="width: fit-content; margin-right: 10px"
        #self
        [ngStyle]="{'margin-left': 'calc(' + value +'% + 10px - '+ self.offsetWidth / 2 +'px)'}">
        {{value}} / 100
      </div>

      <mat-progress-bar
        class="example-margin"
        [color]="color"
        [mode]="mode"
        [value]="value"
        [bufferValue]="bufferValue">
      </mat-progress-bar>
      
    </div>

Here's a demo showcasing the concept: https://stackblitz.com/edit/progressbar-component-gfkdle?file=app%2Fprogress-bar-configurable-example.html

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

Adjusting my navbar to dynamically resize with the changing window dimensions

Seeking guidance on creating a responsive navbar. Currently, I've successfully adjusted the bar's size based on monitor resolution, but the buttons remain static in size. I experimented with using %, vm, and vh, but suspect that there might be a ...

Creating layered images in HTML 5 Canvas using multiple images

How can I draw two images on one canvas without the first image possibly loading slower than the second one and appearing on top of it? I want to ensure that the second image is always drawn on top of the first image. Any suggestions? ...

Issue with generating source map files using Webpack 4 and ts-loader

What mistake am I making here? When I execute webpack -d --config webpack.config.js, the map file is not generated along with bundle files. Here is my webpack.config.js: const path = require('path'); module.exports = { mode: "development" ...

I'm seeking guidance on how to delete a specific ul li element by its id after making an ajax request to delete a corresponding row in MySQL database. I'm unsure about the correct placement for the jQuery

I have created an app that displays a list of income items. Each item is contained within an li element with a unique id, along with the item description and a small trash icon. Currently, I have implemented code that triggers an AJAX call when the user cl ...

What is the best way to assign the value of an HTTP GET request to a subarray in Angular 8

Attempting to store data in a sub-array (nested array) but despite receiving good response data, the values are not being pushed into the subarray. Instead, an empty array is returned. for (var j=0;j<this.imagesdataarray.length;j++){ this.http.g ...

A step-by-step guide on showcasing freshly submitted input data through Ajax

I'm having trouble with this issue! Once I submit the new input, it doesn't show up in the div. Below is my JavaScript code: $('#addVariable').validate({ rules: { variable: {required:true}} , submitHandler: functio ...

Alerts appear immediately upon beginning to type, asking for 8 characters and ensuring both passwords match

Is it possible to notify users that both passwords should match and they need to enter at least 8 characters after typing? There is currently an issue where a notification appears for entering less than 8 characters, but the password reset still proceeds ...

My components views are not being rendered in Angular 4

Currently, I am in the process of learning how to use Angular 4, but I seem to be encountering an issue. Despite having a functioning App template that renders perfectly fine, I am facing difficulties when attempting to render more than one template. I cre ...

Align Bootstrap list items vertically

I'm facing a challenge with aligning the yellow list item blocks vertically in my design. The issue arises because the black dog item is not aligning properly due to its image being shorter than the other two blocks. I've been struggling to find ...

Troubleshooting the error of an undefined RouterModule

Working on implementing lazy loading for my Angular 4 application, I have a total of 18 lazy loaded modules. Upon noticing that fetching these modules is taking some time, I decided to add a loading indicator. Everything worked fine when I added it locally ...

Compilation of Zod record with predefined keys

I need to create a dictionary similar to a zod schema for an object with multiple keys that are already defined elsewhere, all sharing the same value type. Additionally, all keys must be required. const KeysSchema = z.enum(['a', 'b', &a ...

Streamlining Tailwind CSS styles in your React/Next.js components for maximum efficiency

Since implementing Tailwind CSS in my React/Next.js project, I've noticed a decrease in maintainability compared to using traditional CSS or styled-components. Previously, I could easily consolidate style changes, but now I find myself duplicating cla ...

Unable to send event from JavaScript to Component in Ionic

My goal is to notify a component that a script file has finished loading. My approach involves using the onload event of an element to dispatch an event. A service will then register an event listener for this event, waiting for clients to subscribe to an ...

I'm encountering difficulties implementing anchor tags within my single-page application

Currently, I am in the process of learning how to create single page applications with AngularJS using the ui-router module. However, I have encountered an issue where the anchor tag on my main HTML page is not functioning correctly. I am now at a standsti ...

Reloading the current route in Angular 4 using routerLink

Is it possible to refresh the current page by clicking on a link using routerLink? An example of the menu structure I have is: <ul> <li><a routerLink="home">Home</a></li> <li><a routerLink="users">Users</a& ...

To ensure the specificity selector for material UI in React, it is essential to include an empty CSS definition

The styling for the unselected toggle button is working smoothly. However, when you don't define an empty class selector, the style of the selected toggle button does not show: ./App.js import * as React from "react"; { render ...

What is the most effective method to override parent styles while utilizing CSS Modules?

I'm currently using NextJS along with CSS Modules for styling purposes. One of my goals is to adjust the appearance of a component in different scenarios: When it's rendered normally on a page, utilizing props to specify className modifiers. W ...

Showing json information in input area using Angular 10

I'm facing an issue with editing a form after pulling data from an API. The values I retrieve are all null, leading to undefined errors. What could be the problem here? Here's what I've tried so far: async ngOnInit(): Promise<void> ...

Counting up in Angular from a starting number of seconds on a timer

Is there a way to create a countup timer in Angular starting from a specific number of seconds? Also, I would like the format to be displayed as hh:mm:ss if possible. I attempted to accomplish this by utilizing the getAlarmDuration function within the tem ...

Validate multiple email addresses in a single input field, such as adding multiple recipients to the CC field in an email form using

Currently using Angular2 and primeng to create a basic email form with the following input fields: To: Cc: Message: Here is an excerpt of the code from my component class: constructor(private fb: FormBuilder) { this.createForm(); } createForm ...