How to Add Placeholder in Div Tag

Is it possible to add placeholder in div tag

There are lot of options using javascript, but if you want to do it in css. Try this:

[contentEditable=true]:empty:not(:focus):before {
content: attr(data-text)
}
<div contentEditable=true data-text="Enter text here"></div>

How to create a placeholder for DIV that act like textfield?

What I find in other answers is that when using :not(:focus) pseudo class, I have to click again in order to get the blinking cursor and be able to type. Such issue doesn't happen if I click on an area other than the placeholder.

My workaround is simply removing :not(:focus). Even though in this way the placeholder will still be there after I click on the editable div, I'm able to type no matter where in the div I click, and the placeholder disappears immediately after I type something.

BTW, I inspected YouTube's comment div implementation, seems they are doing the same thing, e.g. #contenteditable-root.yt-formatted-string[aria-label].yt-formatted-string:empty:before

.editableDiv1,
.editableDiv2 {
border-bottom: 1px solid gray;
outline: none;
margin-top: 20px;
}

.editableDiv1[contentEditable="true"]:empty:not(:focus):before {
content: attr(placeholder)
}

.editableDiv2[contentEditable="true"]:empty:before {
content: attr(placeholder)
}
<div class="editableDiv1" contentEditable=true placeholder="If you click on this placeholder, you have to click again in order to get the blinking cursor and type..."></div>

<div class="editableDiv2" contentEditable=true placeholder="Click on placeholder is fine, it'll disappear after you type something..."></div>

Placeholder for contenteditable div with minimal JS

The problem is that a <br> is automatically inserted inside a contenteditable div when it is empty. I think that they added <br> to prevent it from collapsing. Here's where they discussed this: Bugzilla.

Here's an example of the collapse prevention I mentioned. You can see that, initially, div has 0 height. However, you can still focus on it. Try typing, then erasing everything. Browser automatically inserts <br> to prevent it from returning to 0 height by adding a <br> which is one line-height high.

div {  border: 1px solid black;}
<div contenteditable="true" data-placeholder="Test"></div>

How do I make a placeholder for a 'select' box?

A non-CSS - no JavaScript/jQuery answer:

<label>Option name
<select>
<option value="" disabled selected>Select your option</option>
<option value="hurr">Durr</option>
</select>
</label>


Related Topics



Leave a reply



Submit