Default input element size

2019-04-24 09:49发布

问题:

The input element by default is size="20" if this is not defined inline or a CSS style rule is attributed to it.

How do you make the default the actual size of the value? For other elements:

<div style="display: inline; width: auto;">
    The box will only fit the width of it's content
</div>

width: auto is all you need. I cannot put a defined width since the value may be longer. For example:

<input id="short" type="text" value="1000" />
<input id="long" type="text" value=" Areally long name is in this input field." />

I want #short to be the size of 1000 (essentially size="4" + the padding) but the #long to be as long as needed. These inputs are coming in programatically so I can't simply put a short class on the one's I want short and a long class on the one's I want long. I would really just like it if I could put:

input { width: auto; }

Anyway to do this?

回答1:

The input element by default is size="20"

This "default size" depends on the browser, the version and your OS. It is not possible to do this in inline styles.

the best solution is to set width and padding so it adds up to 100%

input {
  width: 98%;
  padding: 1%;
}

then set it to absolute left and right 0

<fieldset>
    <input type="text" />
</fieldset>

finally add this css

<style type="text/css">
    fieldset {
      position: relative;
    }

    input {
        position: absolute;
        left: 0;
        right: 0;
    }
</style>


回答2:

Assuming you have each input on its own row in the form, you can set size attribute to the desired size but also add a css of:

input[type="text"] {
  max-width: 100%;
}

This ensures that the field does not overflow the form. This approach gives a visual cue of how much data is expected for short fields (because they will be the right size) while putting a cap on long ones.



回答3:

"How do you make the default the actual size of the value? (...) I would really just like it if I could put: input { width: auto; } Anyway to do this?"

In an Input HTML Element, width is controlled by its size attribute. This is a quick way I use to simulate { width: auto; }, and it is browsers dependance proof:

<input type="text" [size]="element.value.length + 1" #element>