Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get css width from a string

I have a string that I want to display on a web page that is dynamically passed in. I want to be able to dynamically determine the css width needed to display this string and then wrap it in an html element with the exact size needed to display it.

I am currently using javascript and dojo, so answers using those two are fine, but anything else won't work.

More Detail I guess I should clarify. I want to display the string in an input field, so not as simple as a div (I think at least)

like image 554
hbhakhra Avatar asked Feb 14 '12 19:02

hbhakhra


People also ask

How do I make div width as content?

Using inline-block property: Use display: inline-block property to set a div size according to its content.

How do you inherit the width of a parent DIV?

width:inherit inherits width that defined by parent. This makes child width 25%, but if I redefine it with width:100% it will define width of child 50%. I see. So inherit copies the literal expression rather than the value.

How do I change the width of text in CSS?

The width property in CSS is used to set the width to the text, images. The width can be assign to the text and images in the form of pixels(px), percentage(%), centimetre(cm) etc. The width property does not contain padding, borders, or margins. The width property is overridden by the min-width & max-width properties.


1 Answers

If you're wanting to set the <input> length to show all characters in the string, you can set it like so:

var myString = "abcdefg"; // this is what got input dynamically
var myInputElement = document.getElementById('someInput');
myInputElement.size = myString.length;
like image 133
Jonathan M Avatar answered Sep 21 '22 16:09

Jonathan M