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>