Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Adjust HTML Text Input Width to Content

I can't quite find a clear answer on this, and excuse me if there is one I've missed.

I want my text input widths to automatically adjust to the size of the content within them. First with placeholder text than the actual text someone inputs.

I've created the below as an example. Currently, the boxes are far bigger than my placeholder text, causing huge amounts of white space, and it's obviously the same thing when I type in something.

I've tried width auto, some jQuery, and twine and bubble gum I found on the internet. But nothing has worked yet. Any thoughts? Thanks!

HTML:

<span><p>Hello, my name is </p></span>

<span><input type="text" id="input" class="form" placeholder="name"></span>

<span><p>. I am </p></span>

<span><input type="text" id="input" class="form" placeholder="age"></span>

    <span><p> years old.</p></span>

CSS:

.form {
    border: 0;
    text-align: center;
    outline: none;
}

span {
    display: inline-block;
}

p {
    font-family: arial;
}

Fiddle

like image 928
ObbyOss Avatar asked May 29 '15 03:05

ObbyOss


People also ask

How do I make input width fit content?

Use the span. text to fit width of text, and let the input have same size with it by position: absolute to the container.

How do you change the input width of text in HTML?

1. Set width in HTML. In HTML, you can use the width attribute to set the width of an element. Alternatively, you can also use the size attribute to define the width of the <input> .

How do I make input fields grow with text?

To make HTML text input field grow while typing with CSS, we set the max-width style of a contenteditable element. to set the max width of the container div to 200px. to add a contenteditable span inside the div so we can type in the span.


1 Answers

One possible way:

[contenteditable=true]:empty:before {
  content: attr(placeholder);
  color:gray;
}
/* found this online --- it prevents the user from being able to make a (visible) newline */
[contenteditable=true] br{
  display:none;
}
<p>Hello, my name is <span id="name" contenteditable="true" placeholder="name"></span>. I am <span id="age" contenteditable="true" placeholder="age"></span> years old.</p>

Source for CSS: http://codepen.io/flesler/pen/AEIFc.

You'll have to do some trickery to pick up the values if you need the values for a form.

like image 171
sudo rm -rf slash Avatar answered Sep 19 '22 14:09

sudo rm -rf slash