3

I have a readonly HTML <input> that I'd like to display just like a <span>.

However, applying the following CSS causes it to stay as inline-block in Chrome v34 on Windows.

input[readonly] {
  background:none; color:inherit; /* normal colors     */
  border:0; margin:0; padding:0;  /* no special sizing */
  width:auto; display:inline;     /* try to make it inline and auto-size */
}

Demo: http://jsfiddle.net/52vL3/

How can I make the input stop requiring an explicit size, using CSS?

Phrogz
  • 296,393
  • 112
  • 651
  • 745
  • I'm using an `` here instead of a `` or `` because the element can toggle between being editable by the user or not, and I'd prefer not to have to swap elements in and out. – Phrogz May 01 '14 at 20:50
  • 1
    good question... Even with it being inline, there is a space like a padding on the right side when you reduce the width down – Brett Weber May 01 '14 at 20:54
  • example : set the width to 25px and leave everything else the same – Brett Weber May 01 '14 at 20:55
  • 2
    `contenteditable` span instead of an input an option? – j08691 May 01 '14 at 20:59
  • @BrettWeber Thank you, but the size of the content can vary. – Phrogz May 01 '14 at 21:20
  • Maybe a better solution is to replace control on the fly? Using span for read-only; using input - well for input. Otherwise you can try to simulate it: http://jsfiddle.net/52vL3/2/ but I am afraid this is not a universal solution and will require many tweaks – Yuriy Galanter May 01 '14 at 21:23
  • pretty hacky and not a solution but I did this : http://jsfiddle.net/webtiki/52vL3/3/ – web-tiki May 01 '14 at 21:37
  • I wasn't intending that as a solution, but an example of why this idea may be highly flawed. The alternative is less hacky – Brett Weber May 01 '14 at 23:32

1 Answers1

2

There are a bunch of things happening here, but inline-block is not your problem. This can be shown by adding

-webkit-appearance: none

You'll now have an inline input that's still not resizing itself. The problem is that inputs don't automatically size themselves to their value, even when inline.

If it were a type="text" input, you could set size="2" (default is 20) on the input and it would resize it accordingly (albeit with a bit of extra space).

Unfortunately, type="number" ignores the size attribute.

So, you could try using a pattern instead of type="number"

<input value="64" type="text" pattern="\d*" size="2" readonly>

You may want to increase the size when you make it editable though, because the input won't automatically expand to fit wider values.

See this question for an approach to auto-sizing an input as you type.

Or, depending on how you're using it, you might like to consider <span contenteditable="true">

Community
  • 1
  • 1
CupawnTae
  • 14,192
  • 3
  • 29
  • 60