Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indent text exactly one character width

The precondition is that I use monospace as my font-family, but it doesn't seem to work properly, I've tried some solution but neight of them work, my HTML structure is as below:

<!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. use em

    em should be equals to the computed font-size value, but padding-left: 1em; doesn't work:

    em

  2. use px

    padding-left: 32px; makes the same output as padding-left: 1em;.

  3. use ex

    ex should be the computed height of the letter 'x', and it doesn't work either:

    ex

  4. use ch

    OK, webkit doesn't support ch as a css unit.

So how can I write the css to exactly indent the second div one character width, that is, the first '0' should be left-aligned to the letter 'b', without any deviation.

like image 552
otakustay Avatar asked Feb 24 '12 09:02

otakustay


1 Answers

One possible way, although a bit hacky, would be to insert a space before the row using the :before pseudo selector with content:

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

I have no idea as to which browsers support this, but I'd assume all modern browsers would.

http://jsfiddle.net/cavqM/

like image 158
Tatu Ulmanen Avatar answered Oct 01 '22 05:10

Tatu Ulmanen