Adjusting line height dynamically to maintain vertical centering of text when the size of the parent div fluctuates using JavaScript

I'm struggling to create a colored circle with centered text in HTML/Javascript. Here is what I am trying to achieve:

  • Have a colored circle with text perfectly centered horizontally and vertically within it;
  • Dynamically alter the size of the circle from JavaScript while keeping the text centered at all times.

The following code accomplishes the first part:

  • Create the circle using a DIV element styled with appropriate background and border-radius;
  • Add a P element inside the DIV with styles for "text-align: center" and "line-height".

For example:

p.circlecaption {
  text-align: center;
  line-height: 128px;
}
...
<div style="background: #a0a0a0; margin: 0px; width: 128px;
   height: 128px; border-radius: 64px;" id="theCircleDiv">
     <p class="circlecaption" id="theText">TEST!</p>
</div>

While this works for the static case, when attempting to change the size dynamically using JavaScript, setting the line-height property does not keep the text vertically centered as expected. For instance:

var obj = document.getElementById('theCircleDiv');
var sz = '' + (rad*2) + 'px';
obj.style.width = sz;
obj.style.height = sz;
obj.style.margin = '' + (64 - rad) + 'px';
obj = document.getElementById('theText');
obj.style['line-height'] = sz;

Unfortunately, this code resizes and re-centers the circle correctly but fails to maintain vertical alignment of the text. I have tried various solutions such as changing the property to "lineHeight" or using "vertical-align: middle", but none seem to work effectively.

If anyone can provide guidance on how to dynamically set the line-height or suggest an alternative method to keep the text centered within the circle, I would greatly appreciate it. My primary testing browser is Safari on Mac OS, but I am looking for a solution that is compatible across browsers.

Answer №1

Using only CSS, you can easily accomplish this task

#circleContainer {
    display: table-cell;
    text-align: center;
    vertical-align: middle;
}

#centeredText {
    vertical-align: middle;
}

See the live demo here: http://jsfiddle.net/cE87J/

Answer №2

Using flex box makes aligning content much simpler.

div {
  background-color: #ccc;
  height: 50px;
  width: 100%;
  /* Key Component */
  display: flex;
  justify-content: center;
  align-items: center;
}
<div>
  <span>Please Center Me</span>
</div>

Answer №3

Check out this demo. I am utilizing jQuery UI to dynamically set the size, but the resizing function will also function in a JavaScript-only environment.

To begin with, I organized the HTML and moved its styling to CSS.

HTML:

<div id="theCircleDiv">
    <p class="circlecaption" id="theText">TEST!</p>
</div>

CSS:

#theText {
    text-align: center;
    line-height: 128px;
}
#theCircleDiv {
    background: #a0a0a0;
    margin: 0px;
    width: 128px;
    height: 128px;
    border-radius: 64px;
}

JavaScript:

function resize(size) {
    var circle = document.getElementById('theCircleDiv'),
        text = document.getElementById('theText');
    circle.style.width = size + 'px';
    circle.style.height = size + 'px';
    circle.style.borderRadius = (size / 2) + 'px';

    text.style.lineHeight = size + 'px';
}

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

Tips for creating a cohesive group of HTML elements within an editable area

Imagine having a contenteditable area with some existing content: <div contenteditable="true"> <p>first paragraph</p> <p> <img width='63' src='https://developer.cdn.mozilla.net/media/img/mdn-logo-s ...

The AngularJS error message [$rootScope:infdig] is triggered when the number of $digest() iterations exceeds 10 due to a window

It's evident that changing window.location.href/reload to $location.path() resolves the issue. However, using $location.path breaks the app in IE but works in Chrome with window. The purpose behind this is to update a site when a user logs in or out, ...

Ensuring Child Components Update Automatically with Parent Data Changes in Angular 4

Having recently transitioned from AngularJS to Angular 4, I am facing a challenge with my parent and child components. The parent component contains an array of Person objects: people: Person[]; //array of Person model Users can modify this array throug ...

What is causing JavaScript to pass the parameter name instead of the element?

Information: I am currently organizing an array of names into two separate arrays - one for names starting with A-M and the other for names starting with N-Z. My goal is to have each entry represented as an object with the name as the property and an empty ...

Detecting Browser Version Using XML and Javascript

Recently, I created an XML file and attempted to access it using my web browser. It worked perfectly fine in Internet Explorer, but when I tried opening it in other browsers, it failed to function properly. After some investigation, I discovered that the i ...

Navigating through JavaScript links in Selenium (Scrapy) and returning to the initial page: A step-by-step guide

Having some difficulties with pages that have javascript links embedded in them. This issue arises when the page contains a list of cities with javascript in their links. Each link needs to be navigated individually, scraping information and then returning ...

Adjust the Angular menu-bar directly from the content-script of a Chrome Extension

The project I've been working on involves creating an extension specifically for Google Chrome to enhance my school's online learning platform. This website, which is not managed by the school itself, utilizes Angular for its front-end design. W ...

Flask caches JSON files automatically

I am currently working on a visualization app using js and python. The functionality of my app is as follows: There is a textbox in the browser where I input an URL The URL is then sent to Python via Flask In Python, the URL is processed to create ...

on clicking GTM, obtain a different child element

My HTML code is structured as follows: <div onclick="location.href='https://ford-parts-accessories.myshopify.com/products/ash-cup-coin-holder-with-lighter-element?refSrc=6748959244479&amp;nosto=productpage-nosto-1-fallback-nosto-1';&q ...

Refreshing page in Node.js with Express and EJS

I am attempting to automatically refresh the browser page when there are changes in the underlying data model: var request = require('request'); var express = require('express'); var app = express(); var bodyParser = require('body ...

Creating a smooth transition effect on text length using Javascript and CSS: Fading the text as it

I have been searching everywhere for a solution to my issue, but I haven't found it yet. I keep coming across methods to fade text on and off on load, which is not what I need. My goal is to fade some text on the same line, and I have created a mockup ...

Expand a simple object containing an array of simple objects into a single, flat object

update: The issue was incorrectly described at first. I have completely rewritten the description, along with sharing a code snippet that may not be aesthetically pleasing but gets the job done to some extent. Imagining an object: const input = { a: 1, ...

Implementing dynamic drop-down menu changes with JavaScript

Looking to dynamically populate a dropdown menu with options based on the selection in another menu. Specifically, when "Audi" is selected, I want to trigger a JavaScript function that correctly populates the second dropdown with Audi model options. Howe ...

The rangeslider thumb is positioned incorrectly on the track in the Firefox browser. How can this issue be resolved? Please see the code provided

Hey there, I am currently facing an issue with the compatibility of a range slider on different browsers. While it works perfectly on Chrome and Safari, Mozilla browser does not seem to support it. I have been trying my best to resolve this problem witho ...

Developing a versatile code block for handling animations within my project

As I delve into learning jQuery to enhance my new website, I realize that my expertise lies more in web design rather than programming. I find myself struggling to create a versatile function that can be applied to multiple div elements within the HTML. B ...

Encountering difficulties in the installation of the NODE-SCSS module

Encountering an error during the installation of the node-scss module with the following versions: npm version: 6.13.4 node version: v12.16.1 The error message indicates a failure at the postinstall script. Is this related to my node version? I attempted ...

Enable users to modify the URL in the window.open() function

In the code snippet below, a new window opens when a user clicks on a button: $('.loginButton').click(function () { var strString = $("#medlineSearch").val() var strSearch = "http://google.com&query="; var url = strSearch + strSt ...

Ways to update parent and ancestor windows following the closure of child windows

My scenario involves three windows in a hierarchy: 1st - the main window 2nd - a child window that is opened using window.showModalDialog from the 1st window. 3rd - a window that is an ancestor of the 1st window and is opened from the 2nd window using ...

The maximum number of $digest() iterations (10) has been exceeded in $rootScope. Exiting the process

Using UI-Router, I need to check the existing token every time a state change is initiated. The issue only occurs on the initial page load, and disappears upon refreshing the page. Below is the code snippet that I suspect might be causing the error: .run ...

What could be the underlying reason for the unusual behavior observed in this range polyfill implementation?

I am attempting to transform an HTML5 range input into a set of radio buttons. Each radio button corresponds to a value within the original range, with text displaying its value. However, I am encountering an issue where the last piece of text, meant to sh ...