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.



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;    


<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>
%d bloggers like this: