0

When I have a set of Span elements in a container, they are stacked from left to right (and go to the next line when necessary), and more importantly, the width of each of them is automatically set based on how much content is in them.

Is there a way to achieve a similar effect with textfield elements (that have initial values) instead of spans? The automatically adjusted widths is crucial, i.e. I want the textfields to be as wide as their initial values require. I know this can be achieved to some extent in JS, but I prefer a CSS solution.

(I've looked at other questions, but they all seem to target the cases where the textfield width is supposed to change dynamically, not to be set based on the initial value.)

Roozbehan
  • 478
  • 5
  • 15

1 Answers1

0

I'm not sure you can with just css, you can with javascript however! Loop though each input field and set the size relative to the values string length.

$('.in').each(function(i, obj) {
   $(obj).attr('size', $(obj).val().length);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<input type="text" value="test 1" class="in">
<input type="text" value="test 12123131" class="in">
<input type="text" value="test 1414151555151" class="in">
<input type="text" value="test 1123" class="in">
<input type="text" value="test 312321" class="in">

Or even this wonky workaround Auto-scaling input[type=text] to width of value? below is an example of a suggestion on that page

span {
border:1px inset #ddd;
padding:2px;
}
<span contenteditable="true">dummy text</span>
<span contenteditable="true">possible</span>
<span contenteditable="true">duplicate</span>
<span contenteditable="true">haha</span>
<span contenteditable="true">go and view this solution</span>
<span contenteditable="true"><a target="_blank" href="https://stackoverflow.com/questions/8100770/auto-scaling-inputtype-text-to-width-of-value">https://stackoverflow.com/questions/8100770/auto-scaling-inputtype-text-to-width-of-value</a></span>
pokeybit
  • 1,032
  • 11
  • 18