Reputation: 441
I am creating a cipher converter, where I am having trouble adiconar the figures because of the size of the spaces:
Ex: if I give 10 spaces with the keyboard, how many px or Pt have ??
By default my css looks like this:
display: block;
p - block user agent stylesheet
font-family: arial;
.word - arial
font-size: 13.3333330154419px;
.word - 10pt
height: 15px;
margin-bottom: 0px;
* - 0px
margin-left: 0px;
* - 0px
margin-right: 0px;
* - 0px
margin-top: 0px;
* - 0px
padding-bottom: 0px;
* - 0px
padding-left: 0px;
* - 0px
padding-right: 0px;
* - 0px
padding-top: 0px;
* - 0px
text-transform: uppercase;
.word - uppercase
width: 1663px;
rendered Fonts
Arial-27 glyphs
In the tests we do here, font Arial 10pt, is giving 4px each space ... is it?
function getTextWidth(text, font) {
// if given, use cached canvas for better performance
// else, create new canvas
var canvas = getTextWidth.canvas || (getTextWidth.canvas = document.createElement("canvas"));
var context = canvas.getContext("2d");
context.font = font;
var metrics = context.measureText(text);
return metrics.width;
};
/console.log(getTextWidth(' ', "normal 10pt arial"));
Upvotes: 5
Views: 11694
Reputation: 201568
The width of a space, like any character, depends on the font, and it is generally not an integral number of pixels (even though rendering ultimately gets rasterized to pixels or subpixels). For example, for the Arial font, on Windows 7, the width of a space is 569 units, where “unit” is 1/2048 of the font size, to the width of a space is about 0.278 times the font size, em. For a font size of 13.3px, this gives about 3.7px. As such, it gets rounded to 4px in rasterization, but browsers and other programs may treat a sequence of spaces in different ways (and in HTML, the collapse of white space has its role, when applicable).
I have no idea of how this relates to cipher converters, whatever they are. You will probably get more useful answers by describing your original problem, rather than a theoretical question about the width of space.
Upvotes: 6
Reputation: 1333
Its is not possible to tell you exactly , it always depend on the font's metric and way it renders.
See this
example
Upvotes: 0
Reputation: 216
The only way to know is to render the text and measure it.
Something like:
HTML:
<span id="text-to-measure">WWWWWWWWWW</span>
<div id="answer"></div>
JS:
var textNode = document.getElementById('text-to-measure');
var width = textNode.offsetWidth
document.getElementById('answer').innerText = width
But if you are trying to figure out the size for layout purposes there may be a better way.
Upvotes: 0