HomeArticles

Content vs. value

Stefan Baumgartner

Stefan on Mastodon

More on CSS, HTML5

Title’s for all content strategists out there who expect something really meta and with a lot of additional bla bla. Well, this is about HTML Content vs. Input Values.

Margin and Sass expert Kitty Giraudel (check out their awesome blog, btw!) brought up a pretty nice sample on Codepen, showing an input field resizing its width depending on the characters typed in, using the new ‘ch’ unit. The original question was, if there was a CSS only way to recreate this behavior:

Do any of you guys think of a pure CSS way to make an input element wrap around its content? I’m not sure it’s possible actually.

And Kitty is completely right, it isn’t possible. And that’s per definition. input elements are content-less in HTML terms, since they can’t hold content like other HTML elements do:

<p>this is content</p>
<span>this is also content</span>
<input>IMPOSSIBLE</input>

The last one is bogus. Correct way would be &lt;input type="text" value="That is better"&gt;. Auto-width in CSS is only possible with elements that can have content.

If you compare it to other CSS techniques, you’ll notice that input elements can’t have pseudo elements like :before and :after because of the very same reason. Those two elements are placed before and after the content of one element:

<p>
<before goes here>
Content
<after goes there>
</p>

I’m not sure why inputs can’t have content. I assume it has something to do with being connected tightly with the Operating System (at least in the past). Maybe you can help me on that one. The spec defines them as void elements which aren’t allowed to have content in any way.

How can you achieve this behavior CSS only? #

Drop accessibility and use a span.

<span contenteditable>
this is my content
</span>

But hey, not being accessible is not what we want. So use Kitty’s sample. This should work just fine for you!

More articles on CSS

Stay up to date!

3-4 updates per month, no tracking, spam-free, hand-crafted. Our newsletter gives you links, updates on oida.dev, conference talks, coding soundtracks, and much more.