This ranks low on the list of major problems, but I'm trying to make a ZIP code entry input box that has a border image below it with five long dashes, like so:
document.getElementById("zip_entry").focus();
#zip_entry_container {
text-align: center;
background-color: black;
color: white;
padding-bottom: 30px;
padding-top: 20px;
}
input {
font-family: monospace;
display: block;
margin: 0 auto;
color: white;
background-color: black;
outline: none;
padding: 0;
width: 238px;
border: none;
font-size: 80px;
height: 60px;
text-align: left;
}
img {
width: 238px;
}
<div id="zip_entry_container">
<input id="zip_entry" type="text" maxlength=5 pattern="\d*" />
<img src="https://i.sstatic.net/8kNE4.png" />
</div>
Dead simple, right? Here's a CodePen demo
I carefully aligned the input and the image just beneath it in CSS so that, using a monospace font, the numbers align exactly with the dashes beneath them UNTIL the fifth digit is entered, at which point, even though I've set maxlength
to 5, the numbers all shift a few pixels to the left. Here's a video of what I mean, or you can see it yourself in the CodePen link.
I can live with this problem, but I find it really irritating. Any ideas on how I can prevent this default behavior? I've tried messing with keydown
and preventing the event bubble, but it doesn't stop the browser from moving the text--which moves back to the correct location when you lose focus.
I'd also love it if the cursor was aligned over the center of the dash, but the only way I can think to do this is to make five inputs in a row, and trying this caused all sorts of headaches with a pile of event listeners to switch the focus to the next sibling on keyup
, switch to the previous sibling on backspace, and otherwise rewrite all the functionality of an input box.
UPDATE: I thought I could solve this by immediately calling .blur()
when the fifth digit is entered, but the shift still happens for a split second. Gah!
A major problem (especially in terms of browser compatibility) is, that font-family: monospace
results in different fonts being applied depending on OS and browser (see MDN). In the Codepen provided, Chrome on Windows will use Consolas while Firefox seems to use Courier New. If different fonts are used, letters will have different widths and will therefore result in misaligned letters.
If a text-input gets too large for its content, the text will move to the left (as already mentioned and explained by @Vadim Ovchinnikov). to avoid this, there must be enough space for the cursor. Using 5ch as width unit looks like a good solution to me.
Putting this together: