How to indent text exactly one character width
Asked Answered
C

2

13

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.

Calc answered 24/2, 2012 at 9:42 Comment(3)
em and ex measure the font height, not the width. You can try div:last-of-type:before {content:"\00A0"} but that won't work on all browsers either.Fireback
FYI, you can indent a block of text using text-indent:-1ex;padding-left:1ex; (any size of text, multiline text)Carve
@RobW Yes you can, but 1ex is not the width of a character, which is the OP's problem.Fireback
B
16

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/

Bract answered 24/2, 2012 at 9:46 Comment(2)
Yes my target browser (Firefox 6+, Chrome 15+, IE9+) all supports, it seems a good idea, thanksCalc
However it envolves another problem, the ::before pseudo element doesn't make a inherit style, that is, if I use padding-left, a <div><div><div></div></div></div> structure would indent step by step, but using ::before pseudo element doesn't work this way in my "a bit complex" DOM structure...Calc
A
8

Based on the Tatu's approach you can use a unicode representation of a none breakable space like &nbsp;

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

HTH,

--hennson

Adamski answered 24/2, 2012 at 10:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.