I am attempting to make a div
that mimics how a digital readout might display text:
Essentially I want my div to act like a grid of text, where each character is given a space, and no consideration for how words are broken up when going to the next line.
Example:
h | e | l | l | o | w | |
---|---|---|---|---|---|---|
o | r | l | d | |||
b | i | i | i | i | ||
g | h | i | \n | |||
t | h | e | r | e |
Would be how the sentence:
hello world biiiig hi
there
would display.
However, it seems that I am unable to get this behavior, and no combination of white-space
, word-break
, or overflow-wrap
is working...
var par = document.createElement("p");
var text = document.createTextNode(
"Width of box: " + document.getElementById("textBody").clientWidth + "px"
);
par.appendChild(text);
document.body.appendChild(par);
div {
font-family: "Lucida Console", "Courier New", monospace;
border: 1px solid;
margin: 1px;
padding: 0px;
font-size: 1em;
width: 9ex;
white-space: pre-wrap;
word-break: break-word;
overflow-wrap: anywhere;
}
<div id="textBody">hello world biiiig hi
there</div>
Issues with the above snippet:
Bonus question: I am new to em
/ex
units, you might see that I have tried to equate 7ex
with "7 characters wide", but that seems to be off by a few pixels/character. Any guidance on achieving a simple "n
chars wide"?
Thanks to @wazz for the point to <pre>
. This solved the issue of how whitespace is treated, and some more word breaking css gets me closer, but still seeing that the whitespace isn't being wrapped down to the next line:
pre {
border: 1px solid;
padding: 0px;
margin: 5px;
white-space: pre-wrap;
white-space: -moz-pre-wrap;
white-space: -pre-wrap;
white-space: -o-pre-wrap;
overflow-wrap: break-all;
word-break: break-all;
font-size: 1em;
width: 55px;
}
<pre>hello world biiiig hi
there</pre>
You need white-space: break-spaces
.readout {
font-family: "Lucida Console", "Courier New", monospace;
border: 1px solid;
padding: 0 0 0 10px;
margin: 5px;
font-size: 1em;
width: calc((1ch + 10px) * 7);
letter-spacing:10px;
white-space: break-spaces;
word-break: break-all;
}
<div class="readout">hello world biiiig hi
there</div>