0

I tried to use the maxlength attribute of an input element as a CSS width, but it does not seem to work:

input[maxlength] {
  width: attr(maxlength em);
}

According to Mozilla I thought this might be the intended use case. Yes I saw the note. Is there any other way to get it working?

This works, but scales too much.

input[maxlength="2"] {
  width: 2em;
}

input[maxlength="3"] {
  width: 3em;
}
ceving
  • 21,900
  • 13
  • 104
  • 178

1 Answers1

0

You can use the CSS ch unit instead of em. ch corresponds to the width of the 0 character, which you can use in combination with a monospaced font to get input fields of width exactly the same as the maximum content you can fit within.

window.addEventListener('load', function() {
    document.getElementById("sample-btn").addEventListener('click', function(){
        document.getElementById("nick-input").value = "ShadyMedic_00155"
        document.getElementById("msg-input").value = "Sometimes I wish Stack Overflow wasn't so toxic to new users..."
    })
})
input[type=text] {
    font-family: monospace;
}
input[maxlength="16"] {
    width: 16ch;
}
input[maxlength="63"] {
    width: 63ch;
}
<form>
  <p>
    <label for="name-input">Nickname:</label>
    <input type="text" maxlength="16" id="nick-input" required />
  </p>
  <p>
    <label for="msg-input">Comment:</label>
    <input type="text" maxlength="63" id="msg-input" required />
  </p>
  <p>
    <input type="submit" value="Post" />
  </p>
</form>

<button id="sample-btn">Fill with sample data</button>
Shady Medic
  • 111
  • 11