Stephan
Stephan

Reputation: 43053

How to do letter spacing every two letters with CSS only?

Here is my html code:

<span class="number">0102030405</span>

I want to obtain this:

01 02 03 04 05

Here what I have tried:

.number {
    letter-spacing: 2px;
    text-weight: bold;
}

but the spacing is applied between each number. How can I apply the spacing every two numbers ?

Note:
I'm looking for a CSS only solution.

Upvotes: 17

Views: 17688

Answers (3)

Josh Davenport-Smith
Josh Davenport-Smith

Reputation: 5511

For a CSS only solution, without an nth-letter selector you're going to be dealing with workarounds. There is no nth-letter currently (although CSSWG is discussing it) as you'll no doubt know, so here's a possible workaround albeit an ugly one.

If you're happy to tweak for each instance of .number then you could use the following approach based on splitting the pairs of numbers using columns. Works pretty well for the given example:

.number {
    width: 8em;
    display: block;
    word-wrap: break-word;
    columns: 5;
    column-gap: 0.2em;
}

See: http://jsfiddle.net/WgRs6/

The width, columns and column-gap values will need to be tweaked depending on the numbers in the markup as well as the chosen font size. You'd also need to tweak them to change the space between the columns. Unfortunately, this would certainly break if there are numbers with different amount of digits (e.g. 1, 200, 3, 9000, 42, 100000). You asked for splitting between two numbers so hopefully that shouldn't be an issue for you.

Ideally you'd be able to use lettering.js, or any JavaScript which would split your letters into distinct span elements that you could then combine with .number span:nth-child(2n) to add your desired spacing. See: http://jsfiddle.net/SSq7M/

Upvotes: 18

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201866

It cannot be done in CSS, because there is no selector that would refer to, say, the 3rd character in the content of an element or the the first two characters. CSS operates on elements and pseudo-elements, and no currently defined pseudo-element is suitable for this.

If possible, the content should be modified server-side or, if that’s not possible, with client-side JavaScript so that either the character pairs appear as elements or there are space characters between them, e.g. <span class="number">01 02 03 04 05</span>. In the latter case, you can use word-spacing (probably with a negative value) to tune the amount of spacing.

Upvotes: 0

Mijoe
Mijoe

Reputation: 256

I am not sure whether you can do it using css.Anyway you can do this using javascript. The code will be as follows :

 String.prototype.chunk = function(n) {
   var space = [];
   for(var i=0, len=this.length; i < len; i += n) {
     space.push(this.substr(i, n))
   }
   return space
 };

"0102030405".chunk(2).join('  ');

Check Fiddle

Upvotes: 0

Related Questions