thinking stiff

How to make a contenteditable <div> look like an <input> element or <textarea>

Posted in Programming by thinkingstiff on 2012/01/22

Webkit browsers (Chrome/Safari) have a very old, and still outstanding, bug (#38943) with the ::selection pseudo-element: they totally ignore the background-color property.

In my answer to How to style the selected text in textareas and inputs in Chrome? on Stack Overflow, I outline that it is possible, to get around this issue using the contenteditable attribute because the ::selection background-color property is not ignored on <divs>. The look of both <input> and <textarea> elements can be can be duplicated with a <div>, contenteditable, and some CSS.

I further expanded the code in my answer in How do I make an editable DIV look like a text field?. The resulting <input> and <textarea> clones look nearly identical to their native counterparts on Chrome, Safari and Firefox. Opera and IE9 don’t look the same, but are still decent.

Demo: http://jsfiddle.net/ThinkingStiff/FcCgA/

CSS:

textarea {
    height: 28px;
    width: 400px;
}

#textarea {
    -moz-appearance: textfield-multiline;
    -webkit-appearance: textarea;
    border: 1px solid gray;
    font: medium -moz-fixed;
    font: -webkit-small-control;
    height: 28px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
}

input {
    margin-top: 5px;
    width: 400px;
}

#input {
    -moz-appearance: textfield;
    -webkit-appearance: textfield;
    background-color: white;
    background-color: -moz-field;
    border: 1px solid darkgray;
    box-shadow: 1px 1px 1px 0 lightgray inset;  
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 398px;    
}

HTML:

<textarea>I am a textarea</textarea>
<div id="textarea" contenteditable>I look like textarea</div>

<input value="I am an input" />
<div id="input" contenteditable>I look like an input</div>

2 Responses

Subscribe to comments with RSS.

  1. Fernando Paladini said, on 2013/09/28 at 5:37 PM

    Hi Matt!

    I really liked this tutorial. I want know, do you have any idea how to make a “text highlighter” like Facebook do with hashtags?

    I will be glad if you can make a tutorial about this and send me the link. I, of course, will share this on social networks!

  2. Srihari Thalla said, on 2013/12/08 at 7:20 AM

    Thanks Matt, for the contenteditable in HTML part!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: