user9549074
user9549074

Reputation: 23

How to style the last char from input text in CSS?

I have the following snippet which styles one input text element as follows:

Every written char will be placed into a special square box. The problem is that appeared a strange behaviour when I wrote the last char(when maxlength property is reached). The text is just moved some pixels to the left.

That behaviour can be observed here:

#text{
    background-image: url("https://png.pngtree.com/element_origin_min_pic/29/03/20/1656fa8074e9571.jpg");
    width: 255px;
    height: 18px;
    background-size: 20px;
    border: none;
    font-family: monospace;
    font-size: 13px;
    padding-left: 5px;
    letter-spacing: 13px;
}
<br>Cnp: <input type="text" maxlength="13" id="text"/> </br>

Thanks in advance.

Upvotes: 2

Views: 742

Answers (2)

Bal&#225;zs Varga
Bal&#225;zs Varga

Reputation: 1856

That's beacuse your letters are "wider" than they really are, because of letter spacing. To get rid of this (default) behaviour, you need to add a little bit of javascript to reset the elements scrollLeft to 0 after insertion.

Now I just added these handlers via html onkeyup and onchange, as you can see it works.

#text{
    background-image: url("https://png.pngtree.com/element_origin_min_pic/29/03/20/1656fa8074e9571.jpg");
    width: 255px;
    height: 18px;
    background-size: 20px;
    border: none;
    font-family: monospace;
    font-size: 13px;
    padding-left: 5px;
    letter-spacing: 13px;
}
<br>Cnp: <input type="text" maxlength="13" id="text" onkeyup="this.scrollLeft = 0;" onchange="this.scrollLeft = 0;" /> </br>

Upvotes: 2

rpivovar
rpivovar

Reputation: 3438

It looks like the letter-spacing is just too wide. Try changing it to:

letter-spacing: 12.3px;

I arrived at the number 12.3 by just testing it in the browser.

Upvotes: 1

Related Questions