Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

width:auto for <input> fields

Tags:

css

Newbie CSS question. I thought width:auto for a display:block element meant 'fill available space'. However for an <input> element this doesn't seem to be the case. For example:

<body>
  <form style='background:red'>
    <input type='text' style='background:green; display:block; width:auto'>
  </form>
</body>

Two questions then:

  1. Is there a definition of exactly what width:auto does mean? The CSS spec seems vague to me, but maybe I missed the relevant section.

  2. Is there a way to achieve my expected behavior for a input field - ie. fill available space like other block level elements do?

Thanks!

like image 919
richb Avatar asked Oct 09 '22 03:10

richb


People also ask

How do you change the width of the input field?

Set width with JavaScript With JavaScript, you can use the setAttribute() method to set the value of the size attribute on the input text box. You can also dynamically change the width of a text box to match the length of the input. We can easily do this by setting the size attribute on key events.

What is the default width of an input field?

The width will be the value of the size attribute in characters that the input will display. Value should be an integer greater than zero. When not defined, the width of most input elements defaults to 20.

How do you set the height and width of an input type text?

If you simply want to specify the height and font size, use CSS or style attributes, e.g. //in your CSS file or <style> tag #textboxid { height:200px; font-size:14pt; } <!


1 Answers

An <input>'s width is generated from its size attribute. The default size is what's driving the auto width.

You could try width:100% as illustrated in my example below.

Doesn't fill width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input style='width:auto' />
</form>

Fills width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input style='width:100%' />
</form>

Smaller size, smaller width:

<form action='' method='post' style='width:200px;background:khaki'>
  <input size='5' />
</form>

UPDATE

Here's the best I could do after a few minutes. It's 1px off in FF, Chrome, and Safari, and perfect in IE. (The problem is #^&* IE applies borders differently than everyone else so it's not consistent.)

<div style='padding:30px;width:200px;background:red'>
  <form action='' method='post' style='width:200px;background:blue;padding:3px'>
    <input size='' style='width:100%;margin:-3px;border:2px inset #eee' />
    <br /><br />
    <input size='' style='width:100%' />
  </form>
</div>
like image 186
Ben Avatar answered Nov 16 '22 00:11

Ben