如何设置 CSS 中输入文本的最后一个字符的样式?

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

我有以下代码片段,其中 styles 一个输入文本元素如下:

每一个写的char都会被放入一个特殊的方框内。 问题 是当我写最后一个字符时(当达到 maxlength 属性 时)出现了一个奇怪的行为。文本只是向左移动了一些像素。

可以在此处观察到该行为:

#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>

提前致谢。

看起来 letter-spacing 太宽了。尝试将其更改为:

letter-spacing: 12.3px;

我通过在浏览器中测试得到了数字 12.3

那是因为您的字母比实际尺寸 "wider" 大,因为字母间距。要摆脱这种(默认)行为,您需要添加一点 javascript 以在插入后将元素 scrollLeft 重置为 0

现在我只是通过 html onkeyuponchange 添加了这些处理程序,正如您所看到的那样有效。

#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>