Is there a way to make a variable width font act like a fixed width font in HTML? [duplicate]

青春壹個敷衍的年華 提交于 2019-11-28 11:57:31
JoeJ

Not with just CSS. I would recommend you use the popular Lettering.js (you'll need jQuery for it) to generate span tags around each character, then set an width across all the characters.

.monospace > span {
  display: inline-block; /* Enable widths */
  width: 1em;            /* Set width across all characters */
  text-align: center;    /* Even out spacing */
}

Test Case

The only thing I can think of is to put each letter in an HTML element, and style that element something along the lines of:

width: 8px;         /* Whatever fixed width you want here */
display: block;     /* Force the width to be respected. See also: inline-block */
float: left;        /* So it won't be 1-per-line. Not needed for inline-block */
text-align: center; /* So the character appears in the middle of the block */

I'm not familiar with Flex, but if I were to implement this approach, I would put together some Javascript that would generate all the elements for me.

The result should be crappy as proportional fonts aren't made for that.

Nonetheless, you can achieve that with individual span around characters: http://jsfiddle.net/rvYES/

body {
  font: normal 100%/1.5 Arial;
}

span {
  outline: 1px dotted darkred;
}
span:nth-of-type(even) {
  outline-color: blue;
}

.w-fixed span {
  display: inline-block;
  min-width: 1em;
}

I added visual clues (outline) to see what's going on and used min-width just in case, not width.
This method will cause a huge problem of accessibility with screen readers, for blind and partially sighted people using these assistive technologies. Letters being into individual span will be spelled / read out
o
n
e

b
y

o
n
e

w
h
i
l
e

a

n
o
r
m
a
l

p
a
r
a
g
r
a
p
h

w
o
u
l
d

b
e

r
e
a
d

a
s

a

s
e
n
t
e
n
c
e
,

a
s

u
s
u
a
l
.

P
r
e
t
t
y

a
n
n
o
y
i
n
g

e
h
?

pun intended

It's an old question, but I would suggest looking for a suitable fixed-width font that can be used as a webfont that has the features you want. I'm a pretty big fan of Inconsolata, for example.

I'd start with Google Fonts and unselect all categories leaving only Monospace.

You might be able to use the letter-spacing CSS property to get what you want. By definition, monospace fonts have the same character width unlike serif or sans-serif. Using letter-spacing is your best bet W3C Reference

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!