JMP
JMP

Reputation: 4467

Span element with unconstant length

Similar to:

Text width not applying in span

Using the same 'span' idea:

<!DOCTYPE html>
<html>
<script>
str='Just some random text that is about to be encrypted';
function go() {
    crypt.textContent=str;
}
function code() {
    sa=str.split('');
    for (i=0;i<sa.length-1;i++) if (Math.random()<0.5) {t=sa[i];sa[i]=sa[i+1];sa[i+1]=t;}
    crypt.textContent=sa.join('');
}
</script>
<body onload='go();'>
<span style='background-color:red;width:100pt' id='crypt'></span>
<button onclick='code();'>Code</button>
</body>
</html>

The span width still wobbles - but the text is effectively always the same length - at least the letters are the same?

JSFiddle before

JSFiddle after

Upvotes: 1

Views: 58

Answers (1)

aaronk6
aaronk6

Reputation: 2811

The reason for the span width changing is that sometimes two or more space end up near to each other. This makes them collapse into a single space in the rendered result which reduces the amount of characters and changes the span’s width.

Solution 1

Using &nbsp; (non-breaking space) instead of a blank character will solve this. These are rendered even when there are multiple of them near to each other.

To write the &nbsp; character from JavaScript, you’ll need to use the corresponding escape sequence which is \u00A0.

str='Just some random text that is about to be encrypted'.replace(/ /g, "\u00A0");

Solution 2

Another (probably cleaner) solution would be to setting white-space: pre on the span element using CSS:

<span style="background-color: red; width: 100pt; white-space:pre" id="crypt"></span>

Upvotes: 3

Related Questions