使用CSS将非等宽字体强制为固定宽度 [英] Force Non-Monospace Font into Fixed Width Using CSS
问题描述
通过这个我的意思是,使用非等宽字体,你可以强制浏览器渲染每个字符在一个固定的宽度?
你不能用CSS做到这一点。即使你可以,结果也会很糟糕:
.char {outline:1px solid rgba(255,0,0,0.5);}。monospace .char {display:inline -块;宽度:15px; text-align:center;}
< h2 class = boxes>这是一个标题< / h2>< h2 class =boxes monospace>这是标题< / h2>
Is there any way to force a font to be monospaced using CSS?
By this I mean, using a non-monospace font, can you force the browser to render each character at a fixed width?
You can't do this with CSS. Even if you could, the result will look horrible:
If you really do need to do this, you could use JavaScript to wrap each individual character in an element (or just do it by hand):
function wrap_letters($element) {
for (var i = 0; i < $element.childNodes.length; i++) {
var $child = $element.childNodes[i];
if ($child.nodeType === Node.TEXT_NODE) {
var $wrapper = document.createDocumentFragment();
for (var i = 0; i < $child.nodeValue.length; i++) {
var $char = document.createElement('span');
$char.className = 'char';
$char.textContent = $child.nodeValue.charAt(i);
$wrapper.appendChild($char);
}
$element.replaceChild($wrapper, $child);
} else if ($child.nodeType === Node.ELEMENT_NODE) {
wrap_letters($child);
}
}
}
wrap_letters(document.querySelectorAll('.boxes')[0]);
wrap_letters(document.querySelectorAll('.boxes')[1]);
.char {
outline: 1px solid rgba(255, 0, 0, 0.5);
}
.monospace .char {
display: inline-block;
width: 15px;
text-align: center;
}
<h2 class="boxes">This is a title</h2>
<h2 class="boxes monospace">This is a title</h2>
这篇关于使用CSS将非等宽字体强制为固定宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!