如何将文本缩进恰好一个字符宽度

问题描述 投票:0回答:2

前提是我使用monospace作为我的font-family,但它似乎不能正常工作,我尝试了一些解决方案,但其中大多数都有效,我的HTML结构如下:

<!DOCTYPE html>
<style>
  body {
    font-family: monospace;
    letter-spacing: 0;
    word-spacing: 0;
    font-size: 32px; /* large enough to see the effect */
  }
  div:last-of-type {
    padding-left: 1em; /* what's the value? */
  }
</style>
<div>123456</div>
<div>abcdef</div>
  1. 使用em

    em 应该等于 计算的 font-size 值,但是 padding-left: 1em; 不起作用:

    em

  2. 使用px

    padding-left: 32px; 的输出与 padding-left: 1em;.

  3. 相同
  4. 使用ex

    ex 应该是计算出的字母“x”的高度,但它也不起作用:

    ex

  5. 使用ch

    好吧,webkit 支持 ch 作为 CSS 单元。

那么我该如何编写css来精确缩进第二个div一个字符宽度,即第一个'0'应该与字母'b'左对齐,没有任何偏差。

css fonts text-indent
2个回答
16
投票

一种可能的方法,虽然有点 hacky,是使用

:before
伪选择器和
content
:

在行前插入一个空格
div:last-of-type:before {
    content: " ";
    white-space: pre;
}

我不知道哪些浏览器支持此功能,但我假设所有现代浏览器都会支持。

http://jsfiddle.net/cavqM/


8
投票

基于 Tatu 的方法,您可以使用不可破坏空间的 unicode 表示,例如

&nbsp;

div:last-of-type:before {
   content: "\00a0"; /* this is &nbsp; */
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.