What is the best way to determine the accurate size of a div's content?

There are 2 blocks, and the first one has a click handler that assigns the block's scrollWidth to its width property. There is no padding or borders, but when the property is assigned, one word wraps to the next line.

The issue seems to be that scrollWidth returns 270, while the value visible in the web inspector is 270.08. If the width value is set to 270.08, the word won't wrap to the next line.

How can I obtain the real width of the content including the fractional part?

By the way, getComputedStyle(...).width returns "270.078px", but this method is not suitable for cases where the block has overflow. I need the size of the contents.

A second click on the div will set the width to its computed value.

https://jsfiddle.net/0dqzvw4r/

document.querySelector('p').addEventListener('click', function first(event) {
  var width = this.scrollWidth;
  var real = getComputedStyle(this).width;
  
  console.log(width);
  console.log(real);
  
  this.style.width = width + 'px';
  
  this.removeEventListener('click', first);
  this.addEventListener('click', function (event) {
    this.style.width = real;
  });
});
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
}
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>

More complex example:

Similar situation with horizontal scrolling. After assigning the width property, white space is set to normal. The first block gets exactly the scrollWidth, and the second one gets 1 pixel more.

document.querySelector('p').addEventListener('click', function (event) {
  var width = this.scrollWidth;
  console.log(width);
  this.style.width = width + 'px';
  this.nextElementSibling.style.width = width + 1 + 'px';
});
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
  width: 10em;
  white-space: nowrap;
  overflow: auto;
}

p[style] {
  white-space: normal;
}
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>

Answer №1

The function Element.getBoundingClientRect() can be quite useful:

document.querySelector('p').addEventListener('click', function (event) {
  var width = this.getBoundingClientRect().width;
  console.log(width);
  this.style.width = width + 'px';
});
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
}
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>

Answer №2

This code snippet will retrieve the width of an element when clicked and then logs it to the console. It also sets the width of the element to the retrieved value in pixels.

document.querySelector('p').addEventListener('click', function (event) {
  var width = window.getComputedStyle(this).width;
  console.log(width);
  this.style.width = width + 'px';
  
});
body {
  font-family: 'Shrikhand', cursive;
}

p {
  outline: 1px dotted red;
  float: left;
  clear: left;
}
<link href="https://fonts.googleapis.com/css?family=Shrikhand" rel="stylesheet">
<p>How to get correct content size?</p>
<p>How to get correct content size?</p>

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

Issue with specific route causing server to throw 500 error

Recently, I have been working on a small school project that involves creating our own API and connecting it to an Angular front end. While following some tutorials, I encountered an issue where my application started throwing internal server error 500 af ...

The flickering problem with HTML5 DOM

I created a HTML5 game using canvas and DOM elements, but I'm facing an issue with flickering DOM elements while playing. The problem seems to be more prevalent in mobile browsers, particularly Chrome. My game includes a full screen canvas with vario ...

What is the best way to retrieve an object from every function?

I'm dealing with a <div> containing radio buttons: <div id='RB-01'> <span>Item_1</span><input type='radio' name='RB01' value='1'><br /> <span>Item_2</span><inp ...

Is anyone else experiencing issues with loading a font from a CDN? It works perfectly fine on Chrome Browser and Safari for iOS Simulator, but for some reason, it's not loading

It's driving me a bit crazy as I'm not sure where I've gone wrong. I'm currently working with NextJS and have loaded this font into my <Link />. While it displays perfectly on Chrome and Safari in the iOS simulator, it fails to l ...

Failure of Highchart's resizing mechanism when hidden

Check out this AngularJS demo app featuring Highcharts: http://jsfiddle.net/dennismadsen/dpw8b8vv/1/ <div ng-app="myapp"> <div ng-controller="myctrl"> <button ng-click="hideView()">1. Hide</button> <button ng ...

I am attempting to transmit an Error Object through an Axios POST request, but the server is receiving an empty Object

Hey everyone, I'm currently working on creating a Logging Microservice specifically for capturing frontend errors. The goal is to log all errors in a specific format like the example below: catch(err){ sendToLogs({message: 'Could not read input ...

Vue should only activate the element that has been clicked on

I'm currently working on my first Vue project and encountering an issue with triggering a child component within a table cell. Whenever I double click a cell, the `updated` event is being triggered in all child components associated with the table cel ...

Using Javascript and jQuery to modify the element's ID

I've been trying to automate the loading process of articles on my website, but I'm having trouble with the line $(tytul).html(data);. Is there a way to get this working correctly? var numboart = 3; $(document).ready(function(){ for(i=0;i& ...

What is the best way to include multiple selected option values from select2 in form.serialize()?

I am trying to use select2 for selecting multiple options in HTML and then send the selected values as an array using form.serialize() to update a database field. However, my form also contains other input fields. How can I achieve this? Here is my HTML c ...

What is the best approach to link an HTML document to a MySQL Workbench server utilizing JavaScript, Ajax, and PHP?

On my HTML page, users can enter the name of a movie and if it is found in the database, the name will be displayed. I am attempting to establish a connection to the MySQL Workbench Server using JavaScript, Ajax, and PHP. This is what I have implemented s ...

Is there a method to directly download large files from the server without having to wait for the blob response?

I'm currently working on video file requests using axios. I have set the requests with responseType: blob to create a video player once the response is received with window.URL.createObjectUrl(). However, I also have a button that allows the user to d ...

Linkyfy.js does not function correctly with each and not statements

Trying to incorporate a linkifying script on a website, which transforms URLs in text into clickable links. Utilizing the following solution: https://github.com/SoapBox/linkifyjs To make it operational (post-download), the following steps are required: & ...

Ruby on Rails: clearing the asset pipeline cache by hand

While Rails usually clears the asset pipeline cache automatically when files are modified, I am facing a unique situation. I am providing my application as an HTML response to an Ajax request, cross-domain using rack-cors to bypass CORS. The issue arises ...

Exploring the process of linking multiple checkbox fields in a form with an ajax request

I have attempted the following method, but it is not working. I am able to retrieve the name from the form, but nothing gets assigned to the "sharewith" variable. My goal is to assign all selected checkboxes to one id called "sharewith" and then send them ...

Align the bottom borders to the lowest content on each line

I am working on designing my homepage using HTML, CSS, JSP, and JavaScript, focusing on the sale of musical instruments and facilitating communication among users. Right now, I am in the process of creating a site-map for my menu configuration chart using ...

AngularJS is encountering an issue with the callback function, resulting in an error

Currently, I am utilizing the $timeout service in Angular to decrease a variable from 100 to 1 in increments of 1/10 seconds. Although I understand that using the $interval service would be a simpler solution, for this particular scenario, I am focused on ...

When attempting to retrieve the data from a JSON file using an XMLHttpRequest, the result that is returned is [object object]

I am currently studying JSON and found a helpful guide on w3schools. Here is the code provided in the guide: https://www.w3schools.com/js/tryit.asp?filename=tryjson_ajax The guide also includes a sample JSON file: https://www.w3schools.com/js/json_demo.t ...

There was a TypeError encountered while trying to read properties of undefined in Next.js version 13

I've encountered a problem in the title with my post API endpoint that I created in Next.js. The purpose of my endpoint is for form submission, where I gather inputs and send them to my email. Currently, my code successfully sends the email and I rec ...

Error encountered: X.setValue is not a valid function and cannot be used to set the value. However, manually inputting the value as a

When I try to use the line sseTopicString.setValue(sseValueNumber), a Type error is thrown: Uncaught TypeError: sseTopicString.setValue is not a function. Interestingly, if I output the value (string) of sseTopicString before the dot, everything works fin ...

CSS Dialect Debate: Container or Wrapper - Which is the Best Term to

Can you explain the distinction between a container and a wrapper, as well as their respective meanings? ...