Center a sans-serif font vertically with exact precision while adjusting the font size

My issue is an expansion of a previous problem I mentioned in another question, which can be found here Vertically align sans-serif font precisely using jquery/css.

To summarize: I am aiming to align two divs containing text, with one positioned above the other, so that the beginning of the letter A (specifically the lower left point) always aligns with the vertical line of H. Here's an example of what I'm trying to achieve:

The top div has a variable font-size and I want the bottom div to adjust its alignment according to that font size. This adjustment is necessary as I scale my font size based on the window's dimensions.

Check out this demo on jsfiddle.

HTML

<div id="Hideheader" class="Header" style="position: absolute;font-size:40pt;padding:0px;visibility: hidden;width:auto;height:auto;">HEADER</div>
<div id="header" class="Header">HEADER</div>
<div id="menubar" class="menubar">
    <div class="menubutton_left"><a href="#" id="WorkButton">A</a>
    </div>
    <div class="menubutton_middle"><a href="#" id="AboutButton">B</a>
    </div>
    <div class="menubutton_right"><a href="#" id="ContactButton">C</a>
    </div>  <span class="stretch"></span>

</div>

CSS

div.Header {
    font-family:sans-serif;
    text-align:justify;
    white-space: nowrap;
}
div.menubar {
    text-align: justify;
    -ms-text-justify: distribute-all-lines;
    text-justify: distribute-all-lines;
    margin-bottom: 0px;
    position: relative;
}
div.menubutton_left, div.menubutton_middle, div.menubutton_right {
    vertical-align: top;
    display: inline-block;
    *display: inline;
    zoom: 1;
    width:60px;
}
div.menubutton_left {
    margin-left:12px;
}
div.menubutton_middle {
    text-align: center;
}
div.menubutton_right {
    text-align: right;
}
.stretch {
    border: 2px dashed #444;
    width: 100%;
    display: inline-block;
    font-size: 0;
    line-height: 0
}

JAVASCRIPT

resizeHead("#Hideheader", "#header");

$(window).resize(function() {
  resizeHead("#Hideheader", "#header");
});

function resizeHead(p1, p2) {
    var fontsize = parseFloat($(p1).css("font-size"));
    var spacing = parseFloat($(p1).css("letter-spacing"));
    var initWidth = $(p1).width();
    initWidth = initWidth - spacing;
    var outWidth = $(p2).width();

    var s = outWidth / initWidth;
    s = fontsize * s;
    $(p2).css({
        "font-size": s
    });
}

Test resizing your browser window. The alignment issues become more evident at smaller font sizes.

Answer №1

It's possible that I may not fully grasp your query.. However, after reviewing your fiddle, it seems I understand what you're aiming for. Here are some suggestions:

1: Avoid using JavaScript to adjust font sizes. Consider utilizing relative units such as vw, vh, or vmin. These units adjust their size based on the parent container, like so: font-size: 20vw.

This method is much lighter compared to using JavaScript for every window resize event.

2: You've specified a fixed width for your divs, causing layout issues when they shrink below 60px. Remove this fixed width and opt for dynamically calculated widths using calc(100% / 3), ensuring all three divs are correctly positioned.

3: The margin-left on your first div disrupts the layout. Instead, add the margin to the <a> tag within the div:

div.menubutton_left a {
    margin-left:12px;
}

For an updated fiddle incorporating these changes (without any JavaScript), check out the link here: http://jsfiddle.net/ksuTQ/7/

Answer №2

I've encountered a similar issue with my applications in the past, and while I admit my solutions were not always elegant, they did get the job done. @LcSalazar's post is definitely worth checking out, although I have faced challenges in configuring the rest of my page after using elements with relative positioning. However, it seems like you are already going down that path. Start by trying @LcSalazar's suggestion first, and if you're feeling adventurous, give my solution a shot. Consider experimenting with elements like span instead of div, but be aware that this may impact your project significantly.

The main obstacle lies in HTML's limited capability to gather TextMetrics, which is essentially what you're seeking. While canvas elements offer TextMetrics providing width information, obtaining height data proves to be more challenging.

var myCanvas = document.createElement('canvas');
var myContext = myCanvas.getContext('2d');

var myText = "I'm exploring canvas for text measurements!";

var textMetrics = myContext.measureText(myText);

var textWidth = textMetrics.width;

Unfortunately, determining height remains elusive within HTML. Here's an approach I've utilized in the past:

var hiddenDiv =  document.createElement('div');
hiddenDiv.style.visibility = 'hidden';
hiddenDiv.style.position = 'absolute';
hiddenDiv.style.top = '0px';
hiddenDiv.style.left = '0px';
document.body.appendChild(hiddenDiv);

var myText = "Measuring text through a discreet div";

function getTextHeight(text, font)
{
   hiddenDiv.style.font = font;
   hiddenDiv.innerHTML = text;

   return hiddenDiv.clientHeight;
}

var myFont = 'normal 13px Verdana';

var textHeight = getTextHeight(myText, myFont);

You can leverage the obtained text height for resizing or aligning purposes as needed. I chose not to integrate it directly into your project, aiming instead to present a simplified method for acquiring text height without extensive coding. Always remember to define the div's font before measuring it! Hopefully, this provides some assistance!

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

How to Retrieve URL Data in Spring MVC with AJAX / JSON When Loading a New Page

Utilizing Spring MVC in the backend and HTML, AJAX, JSON with jQuery in the frontend, I have a two-page setup. The initial page is named: http://localhost:8080/myproject/start Here, I set up data initialization and execute AJAX/JSON requests using jQuery: ...

Looping through a sequence of asynchronous tasks, utilizing the async/await syntax, writing data to

I'm currently working on a script to download pdf files from a specified URL and save them to my local disk. However, I have encountered an issue where I need each file to be downloaded one at a time with a one-second delay in between (to ensure that ...

Step-by-step guide on replacing a visible div with a new div when a button is clicked

I have organized my website with links on the left sidebar and matching content in the right sidebar, structured within appropriate div elements. My goal is to display only one div at a time when a user clicks on one of the links located on the left side. ...

I am encountering an issue where the msal-browser login process seems to be frozen at the callback

After successfully installing the msal-browser package, I am able to log in. However, I encounter an issue where the screen gets stuck at the callback URL with a code. The samples provided in the GitHub repository demonstrate returning an access token in ...

Creating a dropdown menu with data loaded dynamically using ajax and json, all without relying on jquery

I am looking to populate a few select menus using JSON data retrieved from my PHP script. Each select menu should display different values based on the selections made in the other menus. While I understand how to clear and fill a select menu using JavaScr ...

How to send data to res.render in Node.js?

I'm new to working with node.js. In my index.ejs file, I have included a header.ejs file. Everything seems to be functioning properly except for the fact that I am unable to pass values to the variable status in the header.ejs. index.ejs <html& ...

Connect to the MongoDB database running on localhost using the mongoose library

I am currently learning about the MEAN stack through this helpful tutorial. However, the tutorial assumes a connection to a remote mongodb installation. I have MongoDB already set up and running on my CentOS7 localhost. To modify the mongoose connect line ...

What is the best way to align a div with a fixed width in the center, when it is positioned between two other divs within a parent

I have this HTML (technically JSX) code snippet here: The center div with the class domain-input-parent is supposed to have a fixed width of 400px and stay centered horizontally on the screen. This arrangement ensures that both the domain-label and icon- ...

Fixed Navigation Menu on Top with Specific Width Size

Currently diving into the world of CSS and eagerly following a tutorial on creating a responsive menu for my website. Managed to get it up and running, but hit a few roadblocks along the way: The navigation menu seems to shrink in both desktop and mobile v ...

Error Occurred: Angular View Not Loading

I created a new file named new.html to test navigation, but when I load the page View1.html should appear, instead I see a blank page. Below is the content of my new.html: <!DOCTYPE html> <html data-ng-app="demoApp"> <head> ...

Having difficulty loading the JSON configuration file with nconf

I'm currently attempting to utilize nconf for loading a configuration json file following the example provided at: https://www.npmjs.com/package/nconf My objective is to fetch the configuration values from the json file using nconf, however, I am enc ...

Is it possible for me to define TypeScript interfaces to be used in vanilla JavaScript projects within VSCode?

While using the MS VisualCode editor, I am attempting to implement type checking in my Javascript code. I want to maintain the flexibility of Javascript while also benefiting from type checking interfaces and data structures. Based on the vscode documenta ...

Having trouble locating the bootstrap import statement

Currently, I am working on a project in Angular where I have defined two styles in the angular.json file - styles.css and node_modules/bootstrap/dist/css/bootstrap.min.css. After running ng serve, it shows that it compiled successfully. However, upon ins ...

I'm having trouble anchoring my images to a specific spot on the webpage in HTML

After creating my divs in css and linking them to my index file, I encountered an issue when zooming out of the page. The images would shift to the left while the background remained centered. I needed help figuring out how to keep an image fixed on the pa ...

What is the most effective method for coding an input tag with specific restricted characters?

Introduction I have a unique idea for creating an input field of fixed length where users can fill in the gaps without modifying certain pre-filled characters. For example, I want to display "__llo w_rld!" and let users complete the missing characters. In ...

Customizing HTML element tags in MUI: Best practices

Using the most recent version of MUI (v5) and incorporating CssBaseline from @mui/materials. Typically, in CSS, I would set up my styles like this: body, html, #root { width: 100%; height: 100%; min-height: 100%; margin: 0; padding: 0; font-siz ...

Can Microsoft Edge Developer tool be used to incorporate external programs or code?

This image of msedge-devtools clearly demonstrates my point. I am interested in building a webpage parser using selenium and Microsoft Edge, beyond just JavaScript. I am seeking a way to utilize the Microsoft Edge developer tools (Inspect Element Mode) t ...

Do you think it's feasible to configure cookies for express-session to never expire?

Is there a way to make cookies never expire for express-session? If not, what is the maximum maxAge allowed? I came across some outdated information on setting cookie expiration on SO (over 10 years old) and here on express, which mentions a maxAge of 1 y ...

Extract the data from a deeply nested key within a JSON object

I'm currently working on a function that takes a key (specified as a string) and retrieves its corresponding values from a given JSON object. Here is the JSON data I am working with: [ { "some_key1": [ {"key": "va ...

Unusual situation observed in ExpressJS: Callback function fails to execute

Currently, I am facing an issue with my web app built using expressjs and node. It seems that the functionality is not working correctly. An unusual situation has occurred where accessing the first link in the browser yields the expected results, while th ...