954,598 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

setting an input text field width according to it's font size

Hi all, I'm new here at daniweb.com and I have this question that want to share with you.
Lately I've been trying to set the width of an input so it shows an expecific number of chars according to it's font size. I mean:

<input id="myInput" type="text" value="12345678901234567890" />

as you can see, this is an input with 20 characters in it. What I want to do is to set it's width to match exactly 20 chars. I was wondering if there is some way of doing this width css, maybe something like this:

<style type="text/css">
    #myInput{
        width:20ex; /*it's my understanding that the ex unit should be the x-height for a font*/
    }
</style>


Thanks.

PS:sorry for my english.

unlimited071
Newbie Poster
3 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 
<input type='text' width=20 maxlength=20 value='12345678901234567890'>


http://www.w3schools.com/tags/tag_input.asp

almostbob
Posting Sensei
3,149 posts since Jan 2009
Reputation Points: 571
Solved Threads: 376
 

Make a style, and set the width to 20em (or 21 for some room) in the style.

MidiMagic
Nearly a Senior Poster
3,319 posts since Jan 2007
Reputation Points: 730
Solved Threads: 182
 

@almostbob:
Thanks almostbob but I was wondering how to do this on CSS so I dont have to set the lenght for every input on my site like that.

@MidiMagic
Sorry MidiMagic but that would make the input 20 times the size of the line-height wich is much larger than the width of a char.

taking advantage of almostbob post, i think i could remake my question like this..
wich CSS property (or combination of CSS properties) is equivalent to the following.

unlimited071
Newbie Poster
3 posts since Apr 2009
Reputation Points: 10
Solved Threads: 0
 

You can use the "ch" CSS length unit, which is the width of the font's 0 character. Not sure on overall browser support.

width: 20ch;

abdesigns2011
Newbie Poster
1 post since Oct 2011
Reputation Points: 10
Solved Threads: 0
 

This article has been dead for over three months

Post: Markdown Syntax: Formatting Help
You