How to set an input width to match the placeholder text width

Just in case someone wants to use this with jQuery, that code would be below. Also, if the placeholder attribute doesn't exist in the accepted answer, you'll get errors, which is taken care of as well in the jQuery example below.

$("input[placeholder]").each(function () {
        $(this).attr('size', $(this).attr('placeholder').length);
    });

This can be done only via javascript by setting the size = placeholder length:

input.setAttribute('size',input.getAttribute('placeholder').length);

Here is a code that dose that for all the inputs: http://jsfiddle.net/KU5kN/


I went with Avner Solomon's solution, as proposed in the comments of one of the above sections.

You need a div element wrapping an input and another div element that contains your label:

<div class="input-container">
     <!-- this element is hidden from display and screen readers. -->
     <div class="input-hidden-label" 
          aria-hidden="true">
       Your placeholder text
     </div>

     <input class="input" 
            type="text" 
            placeholder="Your placeholder text"/>
</div>

Assuming the font styles for the input-hidden-label and the input are the same, you will see a line of text alongside the input. The text will be the same length as the input, give or take a few pixels.

You can then apply these styles:

.input-container {
  display: inline-block;
  margin-bottom: 2em;
}

.input {
  display: inline;
  width: 100%;
  font-size: 16px;
  font-family: Times;
}

.input-hidden-label {
  height: 0;
  visibility: hidden;
}

This hides the label by giving it height: 0, and removing visibility. But, the width remains. The div that contains the input and the label matches the width of its longest child. If you then set the input to width: 100%, it will match the parent width, which already matches the placeholder.

See this fiddle.

Caveats

This idea is not very accessible, nor is this solution. You should include a label for the input, and not rely on the placeholder itself as a label.


A workaround i thought of:

  • Make a span element with the same text as placeholder.
  • Measure width of the span element.
  • Set input to the width of the span element.
  • hide span element. display none will not work, use other method.

http://jsfiddle.net/Timar/cwLp3rbo/

var input = document.getElementById('input-1');

// measure width of same text as placeholder
var placeholder =  document.getElementById('input-1-placeholder');


input.style.width = placeholder.offsetWidth + "px"