Adjusting div height according to the size of characters rendered

Is there a way to adjust a div's dimensions based on the characters in a font, such as taller letters resulting in taller divs?

Units like em, ex, and ch are meant to represent font size, but not relative to individual characters.

It's possible that achieving this is not supported in CSS/HTML.

I've included a code example to demonstrate what I mean - the red boundaries represent the divs, while the blue boundaries show the desired output.

body {
  margin    : 5px 0 0 5px;
  padding   : 0;
  display   : inline-flex;
  flex-flow : column;
}

.set {
  display   : inline-flex;
  flex-flow : row;
  padding   : 0;
}

.overlay {
  position   : absolute;
  margin     : 5px 0px 5px 5px;
  width      : 60px;
  box-shadow : 0 0 0 2px blue;
}

.text {
  margin      : 5px 5px 5px 5px;
  font-family : sans-serif;
  font-size   : 32px;
  line-height : 32px;
  box-shadow  : 0 0 0 2px red;
  width       : 60px;
  text-align  : center;
}

.overlay.overlay-1 {
  
  margin-top : -26px;
  height : 13px;
}

.overlay.overlay-2 {
  
  margin-top : -34px;
  height : 22px;
}

.overlay.overlay-3 {
  
  margin-top : -28px;
  height : 23px;
}
<html>
    <body>
    
        <div class="set">

          <div>
              <div class="text">xxx</div>
          </div>
          <div>
              <div class="text">xxx</div>
              <div class="overlay overlay-1"></div>
          </div>

        </div>
    
        <div class="set">

          <div>
              <div class="text">Xxx</div>
          </div>
          <div>
              <div class="text">Xxx</div>
              <div class="overlay overlay-2"></div>
          </div>

        </div>

        <div class="set">

            <div>
                <div class="text">xxy</div>
            </div>
            <div>
                <div class="text">xxy</div>
                <div class="overlay overlay-3"></div>
            </div>
            
        </div>
    </body>
</html>

Answer №1

It appears that achieving this using CSS is not feasible programmatically, as CSS relative heights are based on font dimensions rather than individual characters.

Update: I came across a JavaScript code that can convert a line of text into an image and then determine the image size in pixels. You might find that helpful.

View this post for more information

function measureTextHeight(fontSizeFace) {
      // create a temporary canvas
      var width = 1000;
      var height = 60;
      var canvas = document.createElement("canvas");
      canvas.width = width;
      canvas.height = height;
      var ctx = canvas.getContext("2d");

      // Draw the entire alphabet a-z/A-Z in the canvas
      var text = "o";
      ctx.save();
      ctx.font = fontSizeFace;
      ctx.clearRect(0, 0, width, height);
      ctx.fillText(text, 0, 40);
      ctx.restore();

      // Get the pixel data from the canvas
      var data = ctx.getImageData(0, 0, width, height).data,
        first = false,
        last = false,
        r = height,
        c = 0;

      // Find the last line with a non-transparent pixel
      while (!last && r) {
        r--;
        for (c = 0; c < width; c++) {
          if (data[r * width * 4 + c * 4 + 3]) {
            last = r;
            break;
          }
        }
      }

      // Find the first line with a non-transparent pixel
      while (r) {
        r--;
        for (c = 0; c < width; c++) {
          if (data[r * width * 4 + c * 4 + 3]) {
            first = r;
            break;
          }
        }

        // If we find it, return the height
        if (first != r) return last - first;
      }

      // return 0 in case of an error
      return 0;
    }

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

What is the best way to include a background image in an Angular selector?

I'm having trouble setting a background image for an Angular selector. Here's the code I'm using: <app-highway-card [ngStyle]="{'background-image':'url(https://cdn.pixabay.com/photo/2021/09/04/09/32/road-6597404__340.j ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

The data fail to load correctly with Ajax

I'm having trouble displaying the data from each link in my div. I suspect it may be related to an external .js file that controls the slide up jquery function. Every time a link is clicked, the box slides up but doesn't show any new data. Additi ...

Show elements side by side

I need some assistance. I am trying to find a simple way to horizontally display the circled elements in this image . My attempted solution: .calculator { display: inline-block; } Unfortunately, this did not have any effect. I have provided the HTML ...

Customizing the input field to have a width of 100%

Could someone provide a solution, like a link or working example, for creating input fields with rounded corners that have a width of 100% and a customizable right border? Here is the current structure I am using: <span class="rounded left-corner" ...

Alter the background of only one jumbotron

I have a situation where I need to customize the color of one of the two jumbotrons on my page. Here is the HTML for the jumbotrons: <div class="jumbotron jumbotron-fluid"> <div class="container"> <h3 class="display-5">TEST</h3& ...

Setting up multiple base tags in AngularJS for different modules

When working with angularjs, there is a "#" that needs to be removed. This can be achieved by setting: $locationProvider.html5Mode(true); Additionally, adding the base tag ensures normal functionality when the page refreshes. If <base href="http://exa ...

Unable to extract all elements using simple HTML dom when parsing RSS feed

I've been attempting to extract various details like titles, descriptions, links, images, and dates from an RSS feed located at . However, for some reason, I am unable to retrieve the link tag and image source within the feed. The rest of the data ext ...

Ways to achieve 8 columns in a single row using Javascript and Bootstrap

Recently, I created a simple function for searching movies and manipulating them in the DOM. The issue arises when a movie name is entered and the API response returns around 20-30 recommendations. I wanted to display this fetched data in 8 columns per row ...

Aligning content vertically in Bootstrap 4 so it is centered

I've been struggling to center my Container in the middle of the page using Bootstrap 4. I haven't had much luck so far. Any suggestions would be greatly appreciated. You can check out what I have so far on Codepen.io and experiment with it to s ...

Using Python to access files

I have developed a system that allows me to load image files from HTML. However, after selecting a file and loading it from the front end, I am in need of a Python API to read the selected image file. How can I establish a connection between Python and HTM ...

I'm trying to display hidden forms on a webpage when a button is clicked using the DojoToolkit, but I'm having trouble figuring out what's going wrong with my code

Currently, I am trying to grasp the concepts of Dojotoolkit and my objective is to display a form when a button is clicked. Upon reviewing other examples, my code seems correct to me; however, there appears to be something crucial that I am overlooking but ...

Executing a JavaScript function within the HTML body and passing a variable as an argument to the function

I recently created the following HTML code: <html> <title> Upload Infected File </title> <body> <header id = "header"> <h1 align="center">Upload Malware File</h1> <p align="center"> Pleas ...

Datetimepicker cannot be displayed on this bootstrap version

I am looking to implement a datetime picker for a textbox, but I suspect that I am missing some necessary Bootstrap links. Could someone please point them out for me? Thank you in advance. <div class="form-group row align-items-center justify-conten ...

PHP and Ajax Form Submission Directing to Backend PHP Script

While working on a portfolio, I encountered an issue with the contact form. When I click the submit button to send a message, instead of displaying the bootstrap alert message below the form, the page redirects to the PHP file. Although I receive the emai ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...

defiant underscore refusing to function

I'm currently working on a text editor, but I'm facing an issue with the remove underline functionality that doesn't seem to be working as expected. For reference, you can check out a working code example here: jsfiddle Below is the part of ...

The correct way to write media queries in CSS for the iPhone

After successfully formatting a website for various devices using an online responsive design tester and CSS declarations like @media only screen and (max-width: 480px), I encountered an issue during testing on an actual iPhone. The browser was not computi ...

Loading web pages using ajax and handling relative paths

My method involves using ajax to load HTML files when links on my page are clicked. The process is simplified as follows: links.click(function () { var href = $(this).attr("href"); history.pushState(null, null, href); $.get($(this).attr("href" ...

Ensure the child element is selected immediately following an h2 tag using HTML and CSS

Consider the following brief HTML snippet: <div ...> <h2 class="test">...</h2> <p>...</p> </div> Is it feasible to retrieve the child element (p in this case) after the h2? I have been contemplating poten ...