简体   繁体   中英

How to adjust textbox width based on input that has fixed number of characters but font size may vary?

So I'm receiving a text from a server response :

"AC-8D-9A-7E"

and the text has a fixed number of characters of 11 as above and I want to display it on a textbox in HTML.

However, what I want is that, initially the textbox has a width of 0px and when I received the text from the server, I will then append it to the textbox where the width of the textbox is roughly equal to the width of the text :

在此处输入图像描述

How do i set the width of the textbox so that it is roughly the width of the text ?

 * { margin: 0; padding: 0; box-sizing: border-box; } html { height: 100%; font-size: 1vw; } body { height: 100%; } #container { display: flex; width: 100%; } #code { border-color: black; width: 0px; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width. initial-scale=1.0"> <link rel="stylesheet" href = "style.css"> <title>Document</title> </head> <body> <div id = "container"> <input type = "text" id = "code" disabled> </div> <script> document.getElementById("code");value = "AC-8D-9A-7E"; </script> </body> </html>

If I comment out the #code segment css, the textbox will be looking like so:

在此处输入图像描述

Therefore, how do i retrieve the rough width of the textbox so that it is roughly the same as the width of the text?

Edit: I do not need to consider situations like paste or delete events mentioned in other post as the textbox for me just serve as a display purpose

You can use ch unit. 1ch is approximately equal to the width of 1 character. Since you know the length of the input value is going to be 11 characters, you can set the width of it to be 11ch .

So when you get the response from the server, you can set the width to be 11ch . Although you could make it 12ch and make it look a tad bit better (or you could add padding to the input)

#code {
    width: 11ch;
}

The accepted answer to this question gives a great explanation of the difference between ch and em . Something you may want to consider.

Use the size attribute that specifies the width of input in characters. I used 11 since your display results has 11 chars. Also, I recommend that you use some padding for input field.

<input type="text" size="11" id="code" disabled />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM