【问题标题】:How to indent text exactly one character width如何将文本缩进一个字符宽度
【发布时间】:2012-03-14 18:31:41
【问题描述】:

前提是我使用 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 应该等于 computed font-size 值,但 padding-left: 1em; 不起作用:

  2. 使用 px

    padding-left: 32px; 产生与 padding-left: 1em; 相同的输出。

  3. 使用ex

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

  4. 使用 ch

    好的,webkit 支持 ch 作为 css 单元。

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

【问题讨论】:

  • em 和 ex 测量字体 height,而不是宽度。您可以尝试div:last-of-type:before {content:"\00A0"},但这也不适用于所有浏览器。
  • 仅供参考,您可以使用 text-indent:-1ex;padding-left:1ex; 缩进一段文本(任何大小的文本,多行文本)
  • @RobW 是的,你可以,但 1ex 不是字符的宽度,这是 OP 的问题。

标签: css fonts text-indent


【解决方案1】:

一种可能的方法,虽然有点 hacky,是使用 :before 伪选择器和 content 在行之前插入一个空格:

div:last-of-type:before {
    content: " ";
    white-space: pre;
}

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

http://jsfiddle.net/cavqM/

【讨论】:

  • 是的,我的目标浏览器(Firefox 6+、Chrome 15+、IE9+)都支持,这似乎是个好主意,谢谢
  • 但是它涉及到另一个问题,::before 伪元素不会产生 inherit 样式,也就是说,如果我使用 padding-left&lt;div&gt;&lt;div&gt;&lt;div&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; 结构会逐步缩进,但是在我的“有点复杂”的 DOM 结构中使用 ::before 伪元素并不能以这种方式工作...
【解决方案2】:

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

div:last-of-type:before {
   content: "\00a0"; /* this is &nbsp; */
}

HTH,

--汉森

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-19
    • 1970-01-01
    • 1970-01-01
    • 2021-05-27
    • 1970-01-01
    • 2017-02-07
    • 1970-01-01
    相关资源
    最近更新 更多